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

标签 python list python-3.x

我有这样的东西:

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/

相关文章:

python - 如何在 Kotlin 中解密 AES/CBC 加密字符串?

java - getParcelableArrayList 返回空列表

python - 切片数组,但 Python 中重叠间隔

python - vscode python 转到符号不工作

python - 仅从标签 BeautifulSoup Python 获取直接文本

python - 更新用 imshow()、contour() 和 quiver() 制作的图形

python - python中的间距

vb.net - VB中按第二列对列表进行排序

python - 当我在 selenium python 中获取 MP4 文件的 URL 时如何下载视频? (没有 URLLIB)

java - 如果将泛型类型变量用作类中的字段,它是否应该包含 <T> 表达式?