簡體   English   中英

Python:拆分列表的元素

[英]Python: split elements of a list

作為這個問題的后續內容: 在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']

你的情況更容易,因為你可以利用我們扔掉標簽之前的所有東西:

l = [x.split('\t')[-1] for x in l]
['0238.94', '2.3904', '0139847', '']

注意我們使用[-1]而不是[1],所以當我們拆分('','\\ t')時我們不會炸掉IndexError,結果只得到一個組[''] '-1'表示'最后一個索引',因此當有2個拆分組時-1將等於1,而當只有1個拆分組時則為0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM