我想洗掉python串列串列中的空字串('')。
我的輸入是
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
我的預期輸出應該是:
final_list=[['country'],['India']]
我是 python 的新手,我只是想嘗試這個(注意*下面的嘗試代碼不是故意的)
final=[]
for value in final_list:
if len(set(value))==1:
print(set(value))
if list(set(value))[0]=='':
continue
else:
final.append(value)
else:
(final.append(value)
print(final)
有人可以幫助我實作預期的輸出嗎?以通用的方式。
uj5u.com熱心網友回復:
您可以使用串列理解來檢查子串列中是否存在任何值,并使用嵌套理解來僅檢索具有值的那些
[[x for x in sub if x] for sub in final_list if any(sub)]
uj5u.com熱心網友回復:
您可以使用嵌套串列理解any來檢查串列是否包含至少一個非空字串:
>>> [[j for j in i if j] for i in final_list if any(i)]
[['country'], ['India']]
uj5u.com熱心網友回復:
試試下面的
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)
輸出
[['country'], ['India']]
uj5u.com熱心網友回復:
假設串列中的字串不包含,then
outlist = [','.join(innerlist).split(',') for innerlist in final_list]
但是如果串列串列中的字串可以包含,那么
outlist = []
for inlist in final_list:
outlist.append(s for s in inlist if s != '')
uj5u.com熱心網友回復:
您可以執行以下操作(使用我的模塊sbNative -> python -m pip install sbNative)
from sbNative.runtimetools import safeIter
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
for sub_list in safeIter(final_list):
while '' in sub_list: ## removing empty strings from the sub list until there are no left
sub_list.remove('')
if len(sub_list) == 0: ## checking and removing lists in case they are empty
final_list.remove(sub_list)
print(final_list)
uj5u.com熱心網友回復:
使用串列理解來查找包含任何值的所有子串列。然后使用過濾器獲取此子串列中包含值的所有條目(此處使用 選中bool)。
final_list = [list(filter(bool, sublist)) for sublist in final_list if any(sublist)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370763.html
標籤:Python 蟒蛇-3.x 列表 python-2.7 元组
上一篇:從多個列索引創建多行
