[英]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.