![](/img/trans.png)
[英]How to find the common elements inside two list of values of dictionary in Python without using sets?
[英]Find common dictionary values in list of dictionary - python
我有一個這樣的字典列表:
[{'Y': 80, 'X': 70, 'C': 0, 'L': 'B'}, {'Y': 81, 'X': 71, 'C': 1, 'L': 'C'}, {'Y': 82, 'X': 72, 'C': 2, 'L': 'D'}, {'Y': 82, 'X': 72, 'C': 3, 'L': 'E'}, {'Y': 83, 'X': 73, 'C': 4, 'L': 'F'}]
分解得更容易閱讀
{'Y': 80, 'X': 70, 'C': 0, 'L': 'B'}
{'Y': 81, 'X': 71, 'C': 1, 'L': 'C'}
{'Y': 82, 'X': 72, 'C': 2, 'L': 'D'}
{'Y': 82, 'X': 72, 'C': 3, 'L': 'E'}
{'Y': 83, 'X': 73, 'C': 4, 'L': 'F'}
我想找到'Y'和'X'相同的兩個字典。 然后刪除兩個字典之一並更新結果'C'
{'Y': 80, 'X': 70, 'C': 0, 'L': 'B'}
{'Y': 81, 'X': 71, 'C': 1, 'L': 'C'}
{'Y': 82, 'X': 72, 'C': 2, 'L': 'D'}
{'Y': 83, 'X': 73, 'C': 3, 'L': 'F'}
又快又臟:
d = [
{'Y': 80, 'X': 70, 'C': 0, 'L': 'B'},
{'Y': 81, 'X': 71, 'C': 1, 'L': 'C'},
{'Y': 82, 'X': 72, 'C': 2, 'L': 'D'},
{'Y': 82, 'X': 72, 'C': 3, 'L': 'E'},
{'Y': 83, 'X': 73, 'C': 4, 'L': 'F'}
]
Xs = []
Ys = []
c = 0
out = []
for i in range(len(d)):
obj = dict(d[i]) # Copy the dict at index i
if (obj["X"], obj["Y"]) in XYs:
XYs.append((obj["X"], obj["Y"]))
else:
obj["C"] = c
c = c + 1
out.append(obj)
XYs.append((obj["X"], obj["Y"]))
編輯:通過存儲獨特的元組改進它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.