【发布时间】:2020-12-07 01:26:55
【问题描述】:
我有一个清单:
bigdumblist = [
(0, 0, {'product_id': 2, 'product_uom_qty': 90}),
(0, 0, {'product_id': 3, 'product_uom_qty': 5}),
(0, 0, {'product_id': 5, 'product_uom_qty': 69})
]
我想从列表中删除 'product_id' 不是 2 或 3 的所有项目,如下所示:
[
(0, 0, {'product_id': 2, 'product_uom_qty': 90}),
(0, 0, {'product_id': 3, 'product_uom_qty': 5})
]
我尝试过的:
def not_in(item):
if item["product_id"] is not 2 or 3:
bigdumblist.remove((0, 0, {'product_id': 5, 'product_uom_qty': 69}))
for _, _, item in bigdumblist:
not_in(item)
break
print(bigdumblist)
这很有效,但显然包括(0, 0, {'product_id': 5, 'product_uom_qty': 69}) 不是解决方案。如何正确删除列表中的特定项目?
【问题讨论】:
-
您不应该在迭代列表时修改它。
-
if item["product_id"] not in (2, 3): -
不反对制作新名单
标签: python