【发布时间】:2019-06-20 06:14:12
【问题描述】:
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
【问题讨论】:
-
你能在循环中打印 x 吗?就在分手之后。我认为问题在于某些 x 没有 7 个元素(索引 6)。我不知道为什么 x 是什么,但 python 告诉你,有时你的 split 没有返回足够的元素。
-
在输出中添加(只是一个快照(超过 200 行),每行有 8 个元素。哦,我看到一个空元素。将删除该行并更新结果。
-
在错误行前添加
print(i)(p_start_time_x = x[6];) 以了解错误来自哪个迭代。似乎其中一个文件名太短了。错误前的最后一次打印将显示有问题的文件。