繁体   English   中英

如何删除 python 列表中的“”(空字符串)?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM