gpt4 book ai didi

Python:拆分列表的元素

转载 作者:太空狗 更新时间:2023-10-30 02:04:12 24 4
gpt4 key购买 nike

作为这个问题的后续:split elements of a list in python

给定列表:

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

是不是因为我最后有''?我如何排除它?

最佳答案

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

关于Python:拆分列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23145240/

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