簡體   English   中英

Python:如何從列表列表中刪除包含Nones的列表?

[英]Python: How to remove a list containing Nones from a list of lists?

我有這樣的事情:

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。

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM