【问题标题】:I want to the sum of the 6th column vlaues我想要第 6 列值的总和
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 2019-01-03
    • 2017-06-27
    • 1970-01-01
    • 2021-08-08
    • 2023-01-16
    • 1970-01-01
    • 2018-06-13
    • 2015-06-05
    相关资源
    最近更新 更多