Python:如何从列表中删除空列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4842956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:48:40  来源:igfitidea点击:

Python: How to remove empty lists from a list?

pythonlist

提问by SandyBr

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']

I tried list.remove('') but that doesn't work.

我试过 list.remove('') 但这不起作用。

采纳答案by Sven Marnach

Try

尝试

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]

回答by Sven Marnach

A few options:

几个选项:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

示例会话:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

回答by user225312

>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> list2 = [e for e in list1 if e]
>>> list2
['text', 'text2', 'moreText']

回答by lunaryorn

You can use filter()instead of a list comprehension:

您可以使用filter()而不是列表理解:

list2 = filter(None, list1)

If Noneis used as first argument to filter(), it filters out every value in the given list, which is Falsein a boolean context. This includes empty lists.

如果None用作 的第一个参数filter(),它将过滤掉给定列表中的每个值,该列表False位于布尔上下文中。这包括空列表。

It might be slightly faster than the list comprehension, because it only executes a single function in Python, the rest is done in C.

它可能比列表推导略快,因为它只在 Python 中执行一个函数,其余的都是在 C 中完成的。

回答by Imran

Calling filterwith Nonewill filter out all falsey values from the list (which an empty list is)

调用filterwithNone将从列表中过滤掉所有假值(空列表是)

list2 = filter(None, list1)

回答by jlandercy

I found this question because I wanted to do the same as the OP. I would like to add the following observation:

我发现这个问题是因为我想做与 OP 相同的事情。我想补充以下意见:

The iterative way (user225312, Sven Marnach):

迭代方式(user225312,Sven Marnach):

list2 = [x for x in list1 if x]

Will return a listobject in python3and python2. Instead the filter way (lunaryorn, Imran) will differently behave over versions:

listpython3and 中返回一个对象python2。相反,过滤方式(lunaryorn、Imran)在版本上会有不同的表现:

list2 = filter(None, list1)

It will return a filterobject in python3and a listin python2(see this questionfound at the same time). This is a slight difference but it must be take in account when developing compatible scripts.

它将返回一个filter对象 inpython3和 a listin python2(同时看到这个问题)。这略有不同,但在开发兼容脚本时必须考虑到这一点。

This does not make any assumption about performances of those solutions. Anyway the filter object can be reverted to a list using:

这不会对这些解决方案的性能做出任何假设。无论如何,可以使用以下方法将过滤器对象恢复为列表:

list3 = list(list2)

回答by Arash.H

a = [[1,'aa',3,12,'a','b','c','s'],[],[],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]

b=[]
for lng in range(len(a)):
       if(len(a[lng])>=1):b.append(a[lng])
a=b
print(a)

Output:

输出:

[[1,'aa',3,12,'a','b','c','s'],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]

回答by SUNITHA K

list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
list2 = []
for item in list1:
    if item!=[]:
        list2.append(item)
print(list2)

output:

输出:

['text', 'text2', 'moreText']

回答by Chidi

Adding to the answers above, Say you have a list of listsof the form:

添加到上面的答案,假设你有一个list of lists形式:

theList = [['a','b',' '],[''],[''],['d','e','f','g'],['']]

and you want to take out the empty entries from each list as well as the empty lists you can do:

并且您想从每个列表中取出空条目以及您可以执行的空列表:

theList = [x for x in theList if x != ['']] #remove empty lists
for i in range(len(theList)):
    theList[i] = list(filter(None, theList[i])) #remove empty entries from the lists

Your new list will look like

你的新列表看起来像

theList = [['a','b'],['d','e','f','g']]