python 3 IndexError:列表索引超出范围

时间:2021-02-11 16:39:54

My problem is that the average value on this won't show up as it returns as an error

我的问题是,它的平均值不会显示,因为它返回错误

Traceback (most recent call last):
(file location), line 29, in <module>
    average_score = [[x[8],x[0]] for x in a_list]
(file location), line 29, in <listcomp>
    average_score = [[x[8],x[0]] for x in a_list]
 IndexError: list index out of range

the code

   import csv
class_a = open('class_a.txt')
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
    row[3] = int(row[3])
    row[4] = int(row[4])
    row[5] = int(row[5])
    minimum = min(row[3:5])
    row.append(minimum)
    maximum = max(row[3:5])
    row.append(maximum)
    average = sum(row[3:5])//3
    row.append(average)
    a_list.append(row[0:8])
print(row[8])

this clearly works when I test out the values 0 to 7 ,even if I change the location of the avarage sum I still get the error

当我测试0到7的值时,这显然有效,即使我改变了平均值的位置我仍然得到错误

1 个解决方案

#1


When you call a_list.append(row[0:8]) you're appending an array using only indexes 0, 1, 2, 3, 4, 5, 6, and 7 from row. This means that when you later iterate a_list, the x variable only has indexes up to 7, and you're trying to access 8.

当你调用a_list.append(row [0:8])时,你只使用索引0,1,2,3,4,5,6和7来追加一个数组。这意味着当您稍后迭代a_list时,x变量只有最多7的索引,并且您尝试访问8。

Quick example:

>>> row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = row[:8]
>>> x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> x[7]
7
>>>

#1


When you call a_list.append(row[0:8]) you're appending an array using only indexes 0, 1, 2, 3, 4, 5, 6, and 7 from row. This means that when you later iterate a_list, the x variable only has indexes up to 7, and you're trying to access 8.

当你调用a_list.append(row [0:8])时,你只使用索引0,1,2,3,4,5,6和7来追加一个数组。这意味着当您稍后迭代a_list时,x变量只有最多7的索引,并且您尝试访问8。

Quick example:

>>> row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = row[:8]
>>> x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> x[7]
7
>>>