![](/img/trans.png)
[英]How to cycle over a Python list while removing items until there are none left
[英]Return indexes in list until there are none left
我試圖遍歷列表中不一致的字符串,並且只返回存在的許多字符串(之間還有空格)。 以下是我所擁有的領域:
119|N|Thompson|Compl.
120|N|Thompson|InCompl.
121|W| |
而我想要得到的預期輸出是:
N Thompson Compl.
N Thompson Incompl.
W
我最初嘗試了一個非常基本的功能:
def Split(field):
x = field.split("|")
return x[1] + " " + x[2] + " " + x[3]
但是,由於我的數據不一致並且並不總是具有索引2
和3
,因此它顯然不起作用。 我嘗試枚舉列表,但是我不確定從這里去哪里。
def Split(field):
x = field.split("|")
for idx, val in enumerate(x):
#do stuff
我只想返回很多索引(除了索引0
(它將始終是一個數字))。
您可以使用join
獲取任何列表的字符串:
def Split(field):
return ' '.join(field.split("|")[1:])
如果甚至沒有一個字段,您將需要try
並except
:
def Split(field):
try: return ' '.join(field.split("|")[1:])
except IndexError: return '' #Empty string if there is no index 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.