Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:拆分列表中的元素_Python_List_Split_Element - Fatal编程技术网

Python:拆分列表中的元素

Python:拆分列表中的元素,python,list,split,element,Python,List,Split,Element,作为对这一问题的后续行动: 鉴于清单: l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', ''] 在\t之后如何获取所有内容 我试过: >>> [i.split('\t', 1)[1] for i in t]

作为对这一问题的后续行动:

鉴于清单:

l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', '']
\t
之后如何获取所有内容

我试过:

>>> [i.split('\t', 1)[1] for i in t]                                                                                                                           
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>[i.split('\t',1)[1]表示i-in-t]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器:列表索引超出范围
是因为我在结尾有
'
?我如何排除它

In [175]: l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', '']

In [176]: [i.partition('\t')[-1] for i in l]
Out[176]: ['0238.94', '2.3904', '0139847', '']

或者,如果您只想考虑其中的元素:<代码> \t′/代码>:

In [177]: [i.partition('\t')[-1] for i in l if '\t' in i]
Out[177]: ['0238.94', '2.3904', '0139847']

您的案例更简单,因为您可以利用我们在标签前扔掉所有东西的漏洞:

l = [x.split('\t')[-1] for x in l]
['0238.94', '2.3904', '0139847', '']
请注意,我们使用[-1]而不是[1],因此在拆分(''''\t')时,我们不会使用IndexError,结果只得到一个组
['']

“-1”表示“最后一个索引”,因此当有两个拆分组时,-1将等于1,当只有1时,-1将等于0。

我比你先发布了第二种方法(我使用了
split()
)。@smci干得好!您想在哪里领取奖品?用户1899415,您能接受回答吗?你有两个答案已经快一年了。