Cha*_*ton 4 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.
你可以这样做:
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