简体   繁体   中英

IndexError: list index out of range even though I do not reference a value greater than the length of the list?

I have the following code that I have to run.

Solar = ['Solar',['C','2.6915D-04'],['H','1.0000D+00'],['K','1.0715D-07'],['N','6.7608D-05'],['O','4.8978D-04'],['Ar','2.5119D-06'],['Cl','3.1623D-07'],['Fe','3.1623D-05'],['He','8.5114D-02'],['Mg','3.9811D-05'],['Na','1.7378D-06'],['Si','3.2359D-05'],['Ti','8.9125D-08']]

front = 'cond_initial'

fSolar = open(front+'_'+Solar[0]+'.dat','w')



fin = open(front+'.dat','r')
count = 0
for line in fin:
    count += 1
    if count <= 10: fSolar.write(line)
    if count > 10:
        element = line.split()
        sline = line
        for i in range(1,len(Solar)):
            if element[1] == Solar[i][0]:
                print(element[1])
                sline = line.replace('0.0000D+00',Solar[i][1],1)
        fSolar.write(sline)

However when I do run it, the following error comes up:

    if element[1] == Solar[i][0]:
IndexError: list index out of range

I've tried replacing len(Solar) with 2 to see whether that is the issue, but the same error comes up. Any ideas on how to resolve this? Thanks!

You have blank lines in the file, which should be skipped.

for line in fin:
    count += 1
    if count <= 10: fSolar.write(line)
    if count > 10:
        element = line.split()
        if len(element) < 2:
            continue # skip lines with < 2 columns
        sline = line
        for i in range(1,len(Solar)):
            if element[1] == Solar[i][0]:
                print(element[1])
                sline = line.replace('0.0000D+00',Solar[i][1],1)
        fSolar.write(sline)

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