我在使用这条线时遇到了问题。我不太确定为什么它会给我超出范围的列表索引。到目前为止,我已经尝试了几种解决方案,但都没有奏效。
scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
# Print first 5
a = 0
for score in scoreboardSorted:
print(str(score[0]) + ": " + str(score[1]) + " points")
a = a + 1
if a == 5:
这是这段代码的完整部分
def endGame(points):
scoreboard = []
# Write score to scoreboard
with open("scoreboard.csv", "a") as scoreboardFile:
scoreboardWriter = csv.writer(scoreboardFile)
scoreboardWriter.writerow([name, points])
# Open scoreboard in read mode and store in memory
scoreboardFile = open("scoreboard.csv", "rt")
scoreboardReader = csv.reader(scoreboardFile)
for i in scoreboardReader:
scoreboard.append(i)
print("\nGame over!")
print("Well done " + str(name) + ", you got " + str(points) + " points.")
print("\nTop 5:")
# Sort list
scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
# Print first 5
a = 0
for score in scoreboardSorted:
print(str(score[0]) + ": " + str(score[1]) + " points")
a = a + 1
if a == 5:
break
sys.exit()
回溯是这样的
Traceback (most recent call last):
File "E:\Nea\NEA-PROJECT.py", line 128, in <module>
endGame(points)
File "E:\Nea\NEA-PROJECT.py", line 30, in endGame
scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
File "E:\Nea\NEA-PROJECT.py", line 30, in <lambda>
scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
IndexError: list index out of range
P.S:请不要只发布解决方案并实际详细解释。我是一名仍在努力学习的中学生,如果您能花时间解释一下,我将不胜感激。提前致谢。
最佳答案
您的记分牌
缺少数据。例如,下表中的第二行缺少第二个值。
a = [[1, 2], [3,], [5, 6]]
>>> sorted(a, key=lambda t: t[1])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-341-fea6d7792ad0> in <module>
1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])
<ipython-input-341-fea6d7792ad0> in <lambda>(t)
1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])
IndexError: list index out of range
您可以使用三元组为缺失值提供默认值,例如零。
>>> sorted(a, key=lambda t: t[1] if len(t) > 1 else 0)
[[3], [1, 2], [5, 6]]
关于python - 如何修复列表索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826889/