简体   繁体   English

比较字符串和列表索引错误

[英]comparing strings and list index error

I am trying to run this program in python but it keeps giving me an error that list index is out of range for the if statement line. 我正在尝试在python中运行该程序,但它一直给我一个错误,即if语句行的列表索引超出范围。 But it does print out the "match found" where it has to. 但是它确实在需要的地方打印出“找到匹配项”。

import csv
with open('/Users/jadhav/Documents/Hubble files/m4_hubble_1.csv') as f:
    bl = [[],[],[],[],[]]
    reader = csv.reader(f)
    for r in reader:
        for c in range(5):
            bl[c].append(r[c])

print "The files have now been sorted into lists"
for c in range(0,999):
    if bl[4][c] == "HST_10775_64_ACS_WFC_F814W":
        print "match found"
    else:
        del bl[0][c] 
        del bl[1][c] 
        del bl[2][c] 
        del bl[3][c]
        del bl[4][c]

Looks like the files have less than 999 lines, so bl doesn't grow enough. 文件似乎少于999行,因此bl不够长。 Add exception handling, compute the maximum index beforehand or iterate over the elements differently. 添加异常处理,预先计算最大索引,或对元素进行不同的迭代。

You shouldn't delete items from a list over which you are iterating. 您不应该从要迭代的列表中删除项目。

First you're checking bl[0][0] , then deleting bl[0][0] , causing the later ones to be shifted down. 首先,您要检查bl[0][0] ,然后删除bl[0][0] ,从而使后面的那些向下移位。 There are now 999 items in the list. 现在,列表中有999个项目。

Then you're checking bl[0][1] , which was previously bl[0][2] (the original bl[0][1] is now bl[0][0] ). 然后,您正在检查bl[0][1] ,它之前是bl[0][2] (原来的bl[0][1]现在是bl[0][0] )。

And so on. 等等。

Eventually, when c is 500, you have only 500 items in the list. 最终,当c为500时,列表中只有500个项目。 IndexError ! IndexError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM