[英]remove item from a list within list in dict in python
如果x中的值,我需要刪除y.value形式的值。
x = [[1,2],[2,6],[1,5],[5,6],[5,6],
[10,11], [11,12], [3,4],[4,8],[8,7],[3,7]]
y = {'first':[[1,2],[2,6],[1,5],[5,6]],
'second':[[2,3], [3,7],[7,6],[2,6]]}
for k,v in y.items():
for a in v:
if a in x:
del a
輸出是
{'first': [[1, 2], [2, 6], [1, 5], [5, 6]],
'second': [[2,3], [3, 7], [7, 6], [2, 6]]}
需要:
{'first': [],
'second': [[2, 3], [7, 6], [2, 6]]}
創建一set
不需要的tuple
,然后就地更新字典,並檢查其轉換為元組的內列表項也不在列表中,例如:
unwanted = {tuple(el) for el in x}
y.update((k, [el for el in v if tuple(el) not in unwanted]) for k, v in y.items())
剩下的y
:
{'first': [], 'second': [[2, 3], [7, 6]]}
>>> x = [[1,2],[2,6],[1,5],[5,6],[5,6],
[10,11], [11,12], [3,4],[4,8],[8,7],[3,7]]
>>> y = {'first':[[1,2],[2,6],[1,5],[5,6]],
'second':[[2,3], [3,7],[7,6],[2,6]]}
>>> for k,v in y.items():
y[k] = [a for a in v if a not in x]
>>> y
{'second': [[2, 3], [7, 6]], 'first': []}
使用remove
:
x = [[1,2],[2,6],[1,5],[5,6],[5,6],
[10,11], [11,12], [3,4],[4,8],[8,7],[3,7]]
y = {'first':[[1,2],[2,6],[1,5],[5,6]],
'second':[[2,3], [3,7],[7,6],[2,6]]}
for v in y.values():
for _x in x:
if _x in v:
v.remove(_x)
print(y) # {'first': [], 'second': [[2, 3], [7, 6]]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.