简体   繁体   English

Python 错误:“IndexError:列表索引超出范围”

[英]Python Error: "IndexError: list index out of range"

I'm trying to sort a score by average with data I retrieve from a CSV file, but when I run my code it throws the error :我正在尝试使用从 CSV 文件中检索到的数据按平均值对分数进行排序,但是当我运行我的代码时,它会引发错误:

row[1] = int(row[1])
IndexError: list index out of range

The code I have looks like this:我的代码如下所示:

print("Would you like to see previous results?")
    print("Press 1 to see previous results for your class. Press 2 to close the program")
    answer = int(input())
    if answer == 1:
        print("How would you like data to be sorted?")
        print("Press 1 for average")
        print("Press 2 for highest to lowest")
        print("Press 3 for alphabetically")
        sort_num = int(input())
        if sort_num == 1:
            f = open("Class 2.csv")
            csv_f = csv.reader(f)
            newlist = []
            for row in csv_f:
                row[1] = int(row[1])
                row[2] = int(row[2])
                row[3] = int(row[3])

                average = round(sum(row[1:3])/3)
                row.append(average)
                newlist.append(row[0:4])
            print(newlist)

Could anyone explain why I have this error an show where I'm going wrong?谁能解释为什么我有这个错误显示我哪里出错了?

Try to print the content of row before performing the issued operation.在执行发出的操作之前尝试打印行的内容。

f = open("Class 2.csv")
        csv_f = csv.reader(f)
        newlist = []
        for row in csv_f:
            print("row == {} // type(row) == {}".format(row, type(row)))
            row[1] = int(row[1])
            row[2] = int(row[2])
            row[3] = int(row[3])

If row is void or contains only an element, and in this last case you have to access to element 0 (in code: row[0]), you got this type of error.如果 row 为空或仅包含一个元素,并且在最后一种情况下您必须访问元素 0(在代码中:row[0]),则会出现此类错误。

The printing of type of row is to verify the type of row (yet, I don't think that row has a type different from 'list')行类型的打印是为了验证行的类型(但是,我不认为该行的类型与“列表”不同)

Hope this helps you :-)希望这对你有帮助:-)

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

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