[英]How to remove the '' (empty string) in the list of list in python?
我想刪除 python 列表中的空字符串 ('')。
我的輸入是
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
我預期的 output應該是這樣的:
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)
有人可以幫助我實現預期的 output 嗎? 以一般的方式。
您可以使用列表推導來檢查子列表中是否存在任何值,並使用嵌套推導來僅檢索具有值的那些
[[x for x in sub if x] for sub in final_list if any(sub)]
您可以將嵌套列表推導與any
檢查列表是否包含至少一個不為空的字符串一起使用:
>>> [[j for j in i if j] for i in final_list if any(i)]
[['country'], ['India']]
試試下面
final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)
output
[['country'], ['India']]
假設 list 列表中的字符串不包含,
那么
outlist = [','.join(innerlist).split(',') for innerlist in final_list]
但是如果列表列表中的字符串可以包含,
那么
outlist = []
for inlist in final_list:
outlist.append(s for s in inlist if s != '')
您可以執行以下操作(使用我的模塊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)
使用列表推導查找包含任何值的所有子列表。 然后使用過濾器獲取此子列表中包含值的所有條目(此處使用bool
檢查)。
final_list = [list(filter(bool, sublist)) for sublist in final_list if any(sublist)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.