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

时间:2019-11-10 18:43:06

标签: python

我在这条线上有问题。我不太确定为什么它会使我的列表索引超出范围。到目前为止,我已经尝试了几种解决方案,但是没有一个起作用。

def endGame(points):
    scoreboard = []
    with open("scoreboard.csv", "a") as scoreboardFile:
        scoreboardWriter = csv.writer(scoreboardFile)
        scoreboardWriter.writerow(name, points)
    scoreboardFile = open("scoreboard.csv", "rt")
    scoreboardReader = csv.reader(scoreboardFile)
    for i in scoreboardReader:
        scoreboard.append([i[0], int(i[1])])
Traceback (most recent call last):   File "E:\Nea\NEA-PROJECT.py",
line 127, in <module>
    endGame(points)   File "E:\Nea\NEA-PROJECT.py", line 25, in endGame
    scoreboard.append([i[0], int(i[1])]) IndexError: list index out of range

这应该写出用户的名称和他们获得的分数。令我感到困惑的是,它可以使用名称,并且乐谱已保存在文件中,但它却使我的索引列表超出了范围。

2 个答案:

答案 0 :(得分:1)

您可以在for循环中一次附加整行。否则,当您拥有[i[0], int(i[1])]的行会在scoreboard.csv中发现一行为空(或只有1个字符)的行,然后尝试索引到该行时,将失败。

此外,您还需要将一个可迭代的内容(如列表)传递给writerow方法,因为从the docs可以看到,它只需要一个参数。

def endGame(points):
    scoreboard = []
    with open("scoreboard.csv", "a") as scoreboardFile:
        scoreboardWriter = csv.writer(scoreboardFile)
        scoreboardWriter.writerow([name, points])  # CHANGED
    scoreboardFile = open("scoreboard.csv", "rt")
    scoreboardReader = csv.reader(scoreboardFile)
    for i in scoreboardReader:
        scoreboard.append(i)  # CHANGED

答案 1 :(得分:-2)

import csv
scoreboard = []
with open("scoreboard.csv", "w", newline='') as scoreboardFile:
    scoreboardWriter = csv.writer(scoreboardFile)
    scoreboardWriter.writerow(('bugbeeb', 20))
with open("scoreboard.csv", "r") as  scoreboardFile:
    scoreboardReader = csv.reader(scoreboardFile)
    for row in scoreboardReader:
        scoreboard.append(row)

这应该对您有用