【发布时间】:2019-03-03 02:39:20
【问题描述】:
代码:
import csv
cr = csv.reader(open("filename"))
next(cr)
print (sum(float(x[6]) for x in cr))
但是收到错误IndexError: list index out of range
【问题讨论】:
标签: python python-2.7 indexoutofboundsexception
代码:
import csv
cr = csv.reader(open("filename"))
next(cr)
print (sum(float(x[6]) for x in cr))
但是收到错误IndexError: list index out of range
【问题讨论】:
标签: python python-2.7 indexoutofboundsexception
第 6 列的索引是 5 而不是 6,所以更改:
print (sum(float(x[6]) for x in cr))
到:
print (sum(float(x[5]) for x in cr))
但是如果您在更改后仍然收到IndexError,可能是您的 CSV 中的某些行没有第 6 列,在这种情况下,您可以在生成器表达式中添加一个条件来跳过那些没有 6 列:
print (sum(float(x[5]) for x in cr if len(x) >= 6))
【讨论】: