简体   繁体   中英

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. 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. 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. There are now 999 items in the list.

Then you're checking bl[0][1] , which was previously bl[0][2] (the original bl[0][1] is now bl[0][0] ).

And so on.

Eventually, when c is 500, you have only 500 items in the list. IndexError !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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