Python:如何从列表列表中删除包含Nones的列表?

时间:2014-04-18 05:08:15

标签: python list python-3.x

我有这样的事情:

myList = [[1, None, None, None, None],[2, None, None, None, None],[3, 4, None, None, None]]

如果列表中的任何列表有4个Nones,我想删除它们,因此输出为:

myList = [[3, 4, None, None, None]]

我尝试使用:

for l in myList:
    if(l.count(None) == 4):
        myList.remove(l)

但是,即使我知道if语句正确执行导致了这一点,它仍然只会删除其中的一半:

[[2, None, None, None, None], [3, 4, None, None, None]] 

我设法使用它来使用它,但它不可能是正确的:

for l in myList:
    if(l.count(None) == 4):
        del l[0]
        del l[0]
        del l[0]
        del l[0]
        del l[0]

myList = list(filter(None, myList))

这样做有什么好办法?提前致谢。我正在使用python 3.3。

1 个答案:

答案 0 :(得分:6)

你可以这样做:

my_new_list = [i for i in myList if i.count(None) < 4]

[OUTPUT]
[[3, 4, None, None, None]]

问题是你在迭代它时修改列表。如果你想使用那种循环结构,那就改为:

i = 0
while i < len(myList):
    if(myList[i].count(None) >= 4):
        del myList[i]
    else:
        i += 1