Python- 删除项目

Python- Removing items

我想从名为 mom 的列表中删除项目。我有另一个名为 cut

的列表
mom= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]
cut =[0, 9, 8, 2]

我如何从妈妈那里删除除零之外的内容?

我想要的结果是

mom=[[0,1],[0,6,7],[0,11,12,3],[0,5,4,10]]
>>> [[e for e in l if e not in cut or e == 0] for l in mom]
[[0, 1], [0, 6, 7], [0, 11, 12, 3], [0, 5, 4, 10]]

这就是我对列表理解的处理方式。

mom= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]
cut =[0, 9, 8, 2]
mom = [[x for x in subList if x not in cut or x == 0 ] for subList in mom ]

Ingnacio 和 Dom 提供的答案非常完美。可以用更清晰易懂的方式来做同样的事情。请尝试以下操作:

妈妈= [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]

cut =[0, 9, 8, 2]

for e in mom:



for f in e:


if f in cut and f != 0:


e.remove(f)  #used the remove() function of list

print(mom)

对于 Python 中的新手来说要容易得多。不是吗?

给定 cut=[0,9,8,2] 和 妈妈 = [[0,8,1], [0, 6, 2, 7], [0, 11, 12, 3, 9], [0, 5, 4, 10]]

假设从切割清单中删除了 0 个元素

切=[9,8,2]

结果=[] 对于妈妈的e: result.append(列表(集合(e)-集合(剪切)))

o/p 结果

[[0, 1], [0, 6, 7], [0, 11, 3, 12], [0, 10, 4, 5]]