python - 如何修复列表索引超出范围?

标签 python 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:

这是这段代码的完整部分

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/

相关文章:

python - 索引 Pandas 数据帧 : integer rows, 命名列

Python-类型错误 : expected string or buffer

python - 使用 Paramiko 将文件从一个目录移动到另一个目录

python - 如果其他行遵守某些条件,我如何删除基于行?

python - 什么是对关键字搜索的结果总数进行数据挖掘的合适方法?

c# - 如何使用 Linq 从 List<Rectangle[]> 中选择矩形

python - 嵌套列表到嵌套字典 python3

c# - 在另一个列表中添加列表副本的最佳方法是什么?

python - 对csv文件进行解析和分析

java - 我可以将字符串转换为具有泛型类型的列表吗?