简体   繁体   English

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

[英]How to fix list list index out of range

I am having problems with this line.我遇到了这条线的问题。 I am not really sure why it gives me list index out of range.我不太确定为什么它让我的列表索引超出范围。 I've tried couple of solutions so far none of them worked.到目前为止,我已经尝试了几种解决方案,但都没有奏效。

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

This is supposed to write the name of the user and the score they achieved.这应该写用户的名字和他们获得的分数。 The thing that confuses me is that it works the name and the score is saved on the file, but it gives me index list out of range.让我感到困惑的是它的名称和分数保存在文件中,但它让我的索引列表超出范围。

You can just append the whole row at once in the for loop.您可以在 for 循环中一次 append 整行。 Otherwise the line you had [i[0], int(i[1])] will fail when it finds a row in the scoreboard.csv that is empty (or has only 1 character), and then it tries to index into that.否则,当它在scoreboard.csv中找到为空(或只有 1 个字符)的行时,您拥有[i[0], int(i[1])]的行将失败,然后它会尝试对其进行索引.

Also you need to pass an iterable (like a list) to the writerow method, since as you can see from the docs it only takes one argument.此外,您需要将一个可迭代的(如列表)传递给writerow方法,因为从文档中可以看出,它只需要一个参数。

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
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)

this should work for you这应该适合你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM