python - for循环,分割字符串,将部分字符串保存到新列表,IndexError : list index out of range - works for one part of string and not the other

标签 python list

Python 新手。我有一个文件名列表,我在 for 循环中将其分开。我想将其中一些列放入一个新列表中。它适用于 x[0],但不适用于 x[6]。当我打印 x[0] 和 x[6] 时,它们都是字符串并且都有值。

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)

输出

['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'...]

运行循环时出现的错误。

---------------------------------------------------------------------------
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

最佳答案

您的问题是某些文件名没有足够的下划线分隔部分。假设如果他们确实不这样做,则 start_time 元素不相关,您可以这样做:

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

关于python - for循环,分割字符串,将部分字符串保存到新列表,IndexError : list index out of range - works for one part of string and not the other,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674214/

相关文章:

python - pylab散点图出现转置

python - python中的正则表达式搜索

python - itertools.dropwhile 有困难

python - 在 Python 中创建二维网格

java - 如何修复 'Concurrent writes on cassandra lists issue when data in the lists is getting mixed' ..?

list - Prolog 添加 N 到 0 到列表

python - 根到叶算法错误

python - 计算数组中选定差异的有效方法

使用深度名称向量作为索引替换嵌套列表

python - 在Python中修改3D数组