Python Lambda Function — List Index out of Range
我刚接触过Python中的lambda函数,我正在尝试使用一个csv文件。
我的文件eggs.csv将以空文件开始。csv文件的目的是为一个小游戏存储高分,这是我为了好玩而建立的。文件中的每一行将包含三个值:用户名、高分和日期/时间。
这段代码所做的(或者更确切地说,应该做的)是读取csv的每一行,并将每一行存储为自己的列表。如果csv少于三行,它会附加一些内容(为了测试的目的)。然后将这些列表中的每一个附加到
如果EDOCX1中有7行或更多行(0),则根据行列表的第2项(分数)按降序对它们进行排序。它检查
如果
我正在使用lambda函数进行排序,当我运行它时会引发此错误:
1 2 3 4 5 6 7 8 | C:\Users\kyle\Desktop\csv_workspace>python text_csv.py [[], ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018']] Traceback (most recent call last): File"text_csv.py", line 29, in <module> current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) File"text_csv.py", line 29, in <lambda> current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) IndexError: list index out of range |
为什么列表索引(可能是lamba函数)超出范围?更重要的是,我如何修复它?
请参阅下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | user ="Kyle" high_score = randint(1, 1000) day = time.strftime("%m/%d/%Y") with open('eggs.csv', 'r', newline='') as csvfile: scores_reader = csv.reader(csvfile, dialect="excel") current_scores = [] for row in scores_reader: current_scores.append(row) if len(current_scores) < 3: for i in range(0, 3): current_scores.append(['Kyle', 40+i, day]) if len(current_scores) >= 7: current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) print(current_scores) if high_score > int(current_scores[-1][1]): # if player high score is higher than any of current scores current_scores.remove(current_scores[-1]) # remove last item in list current_scores.append([user, high_score, day]) # append player high score current_scores = sorted(current_scores, key= lambda x: x[1], reverse=True) else: current_scores.append([user, high_score, day]) print(current_scores) current_scores = sorted(current_scores, key=lambda x: x[1], reverse=True) with open("eggs.csv", 'w', newline="") as csvfile: scores_writer = csv.writer(csvfile, dialect="excel") for row in current_scores: scores_writer.writerow(row) |
号
开始处似乎有空行:
1 | [[], ['Kyle', 40, '03/23/2018'], ['Kyle', 41, '03/23/2018'], ['Kyle', 292, '03/23/2018']] |
第一个条目