Python编程阅读

2024-09-29 01:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

count = 0
for row in file:
    count+=1
    segment = row[:-1].split(", ")
    num += 1
    if segment[14] == '>50K':
        count1 += 1
        print ("no of line are", count1)
    elif segment[14] == '<=50K':
        count2 += 1
        print ("no of line are", count2)

所以这段代码可以工作,但是如果我注释掉这两个打印语句,我的代码会给我这个错误

IndexError: list index out of range

有人能向我解释为什么以及如何解决这个问题,因为我真的很困惑。你知道吗


Tags: ofno代码inforcountlinesegment
3条回答

思考一下这个koan:

segment = "".split()   # returns []
s = segment[14]

。。。访问一个不存在的列表项的声音是什么?

可能错误发生在您尝试访问segment[14]的地方。你知道吗

在少于15个段的行上,您根本无法访问[14]。你知道吗

您可能希望在之前检查len(segments),或者希望捕获此异常并适当地处理它。你知道吗

代码的另一个问题是:没有定义count1和count2,就像在第一行中将count设置为0一样。你知道吗

相关问题 更多 >