Rachel Terry
Rachel Terry

Reputation: 35

for loop, split string, save parts of string to new list, IndexError: list index out of range - works for one part of string and not the other

New to python. I have a list of filenames that I split apart in a for loop. I want to take a few of those columns and put them in a new list. It works for x[0] but not for x[6]. When I print x[0] and x[6], they both are strings and both have a value.

p_type=[]; p_start_time=[]; p_end_time=[];

for i in precise_links: #precise_links is list of filenames
    x = i.split('_')
    print(x)
    p_type_x = x[0]; p_type.append(p_type_x)
    p_start_time_x = x[6]; p_start_time.append(p_start_time_x)

#To show you x
print(x)

#To show you what each x part is/type
print(x[0]) 
type(x[0])
print(x[6])
type(x[6])

print(p_type)

Output

['S1A', 'OPER', 'AUX', 'POEORB', 'OPOD', '20180829T120853', 'V20180808T225942', '20180810T005942.EOF']
['S1A', 'OPER', 'AUX', 'POEORB', 'OPOD', '20171021T121400', 'V20170930T225942', '20171002T005942.EOF']
['S1A', 'OPER', 'AUX', 'POEORB', 'OPOD', '20150525T122539', 'V20150503T225944', '20150505T005944.EOF']
['S1A', 'OPER', 'AUX', 'POEORB', 'OPOD', '20180703T120727', 'V20180612T225942', '20180614T005942.EOF']
['S1B', 'OPER', 'AUX', 'POEORB', 'OPOD', '20171015T111433', 'V20170924T225942', '20170926T005942.EOF']
['S1A', 'OPER', 'AUX', 'POEORB', 'OPOD', '20150605T122809', 'V20150514T225944', '20150516T005944.EOF']
....

['S1B', 'OPER', 'AUX', 'POEORB', 'OPOD', '20160620T141641', 'V20160528T225943', '20160530T005943.EOF']

S1B

str

V20160528T225943

str

['S1A', 'S1A', 'S1A', 'S1A', 'S1B', 'S1A', 'S1B', 'S1B', 'S1A'...]

The error I get when running the loop.

---------------------------------------------------------------------------
IndexError - Traceback (most recent call last)

<ipython-input-131-2cbe5599886f> in <module>= 13     
p_start_time_x = x[6]; #p_start_time.append(p_start_time_x)

IndexError: list index out of range

Upvotes: 1

Views: 75

Answers (2)

Rachel Terry
Rachel Terry

Reputation: 35

What I ended up doing.. All the file names should be in the correct order and I wanted my lists to be the same length (to work with later), so I just threw out any names that did not meet the criteria (length of 8)

p_type=[]; p_start_time=[]; p_end_time=[];

for i in precise_links:
    x = i.split('_')
    if len(x) == 8:
        p_type.append(x[0])
        p_start_time.append(x[6])

Upvotes: 0

Tomerikoo
Tomerikoo

Reputation: 19414

Your problem is that some filenames don't have enough parts seperated with underscores. Assuming that if they really don't, start_time element is not relevant, you could do:

p_type=[]
p_start_time=[]

for i in precise_links: #precise_links is list of filenames
    x = i.split('_')
    try:
        p_type.append(x[0])
        p_start_time.append(x[6])
    except IndexError:
        print("Bad file encountered - {}".format(i)
        continue

Upvotes: 1

Related Questions