我有这样的东西:
myList = [[1, None, None, None, None],[2, None, None, None, None],[3, 4, None, None, None]]
如果列表中的任何列表有 4 个无,我想删除它们,所以输出是:
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
关于Python:如何从列表列表中删除包含 Nones 的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23147735/