列表索引超出范围 - 找不到原因

时间:2016-02-10 13:29:09

标签: python

我正在编写代码将数据排序到列表中,然后安排这些列表,但我一直得到:

  

builtins.IndexError:列表索引超出范围

代码中的数据是:

Class 1: 
Matthew 5   5   1
Paul    9   3   6
Sara    9   4   2
Nicholas3   2   4
Larry   5   2   5
Philip  4   4   6
Patricia7   7   7
Gary    0   9   4
Marie   8   7   1
Scott   4   3   2

Class 2: 
Heather 10  2   3
Lawrence 2  4   4
Stephen 1   6   8
Robert  3   5   4
Shawn   9   6   6
Michelle 6  7   4
Chris   10  4   2
Teresa  5   5   6
Dennis  7   8   1
Rose    8   3   4

Class 3:
Jojo    10  3   9
Sarah   1   2   8
Jerry   5   3   7
Aaron   7   8   5
Carl    3   7   5
Christine   9   4   4
Jennifer    2   8   2
Linda   8   8   1
Justin  4   6   3
Emily   2   4   7

代码:

import csv

while True:
    ClassNumber = int(input("What class would you like to see the results for?"))
    if 1<= ClassNumber <=3:
        break
    print("That class does not exist. Please choose from 1,2 or 3")

if ClassNumber == 1:
    ClassFile = "class1scores.csv"
elif ClassNumber == 2:
    ClassFile = "class2scores.csv"
else:
    ClassFile = "class3scores.csv"

OpenFile = open(ClassFile, "r")
scores = csv.reader(OpenFile)    

newlist = []

for row in scores:
    row[1] = int(row[1])
    row[2] = int(row[2])
    row[3] = int(row[3]) 

    HighestScore = max(row[0:3])
    row.append(HighestScore)

    AverageScore = round(sum(row[0:3])/3)
    row.append(AverageScore)

1 个答案:

答案 0 :(得分:4)

默认情况下,csv.reader假定逗号是字段分隔符,但您的数据是制表符分隔的。因此,每行只有一个项目,而不是四个。

scores = csv.reader(OpenFile, delimiter="\t")