【发布时间】:2018-03-23 22:47:33
【问题描述】:
我是 Python 中 lambda 函数的新手,我正在尝试使用 CSV 文件。
我的文件 egg.csv 一开始是空的。 CSV 文件的目的是存储我为好玩而构建的小游戏的高分。文件中的每一行将包含三个值:用户名、高分和日期/时间。
这段代码所做的(或者更确切地说,应该做的)是读取 CSV 的每一行,并将每一行存储为自己的列表。如果 CSV 少于三行,它会附加一些(出于我的测试目的)。然后将这些列表中的每一个附加到current_scores。
如果current_scores 中有 7 行或更多行,则它会根据行列表的第 2 项(分数)按降序对它们进行排序。它检查current_scores 列表中的最后一项,如果玩家的high_score(暂时硬编码)高于该项,则删除最后一项,并附加新列表(这将是一个新的CSV 中的行),玩家得分为current_scores。
如果current_scores 中的项目少于七个,则简单地附加玩家的信息。然后根据其中每个列表的分数对列表进行排序(列表中的第二项是分数)。
我正在使用 lambda 函数进行排序,运行时出现此错误:
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 函数)超出范围?更重要的是,我该如何解决?
请参阅下面的代码:
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)
【问题讨论】:
-
因为
[[], ['Kyle', 40, '03/23/2018'] .. ]的第一项是[],所以item[1]超出范围。考虑改成lambda x: x if len(x)> 0 else None
标签: python python-3.x lambda