gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:41:44 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com