I am trying to append a lengthy list of rows to the same variable. It works great for the first thousand or so iterations in the loop (all of which have the same lengths), but then, near the end of the file, the rows get a bit shorter, and while I still want to append them, I am not sure how to handle it.
The script gives me an out of range error, as expected.
Here is what the part of code in question looks like:
ii = 0
NNCat = []
NNCatelogue = []
while ii <= len(lines):
NNCat = (ev_id[ii], nn1[ii], nn2[ii], nn3[ii], nn4[ii], nn5[ii], nn6[ii], nn7[ii], nn8[ii], nn9[ii], nn10[ii], nn11[ii])
NNCatelogue.append(NNCat)
ii = ii + 1
print NNCatelogue, ii
Any help on this would be greatly appreciated!
I’ll answer the question you didn’t ask first 😉 : how can this code be more pythonic?
Instead of
you should do
During each pass
iiwill be incremented by one for you andlinewill be the current line.As for your short lines, you have two choices
None) to fill in when you don’t have a real valuenn1,nn2, …,nn11to see if they are large enoughThe second solution will be much more verbose, hard to maintain, and confusing. I strongly recommend using
None(or another special value you create yourself) as a placeholder when there is no data.