Python:如何从列表中删除空列表? [英] Python: How to remove empty lists from a list?
本文介绍了Python:如何从列表中删除空列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,其中有空列表:
I have a list with empty lists in it:
list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
如何删除空列表,以便获得:
How can I remove the empty lists so that I get:
list2 = ['text', 'text2', 'moreText']
我尝试了list.remove(''),但这不起作用.
I tried list.remove('') but that doesn't work.
推荐答案
尝试
list2 = [x for x in list1 if x != []]
如果您想摆脱虚假"的一切,例如空字符串,空元组,零,您也可以使用
If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use
list2 = [x for x in list1 if x]
这篇关于Python:如何从列表中删除空列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文