查找字典中多个集合的相等值



我有一本字典:

d = {"key1": [a,b,c], "key2": [b,c,d,e], "key3": [a,e]}

我需要比较值以得到如下结果:

"Key1 and Key2" have 2 equal values # b, c
"Key1 and Key3" have 1 equal values # a
"Key2 and Key3" have 1 equal values # e

更新,我试过了:

for v in enumerate(d):
for k in d.keys():
if v[1] != k:
print("{} compare with{}".format(v[1], d[k]))

但这不是解决方案

您可以使用itertools.combinations获得组合键,然后使用&集合运算符获得相交。

from itertools import combinations
dic = {"key1": ['a','b','c'], "key2": ['b','c','d','e'], "key3": ['a','e']}
for (k1, l1), (k2, l2) in combinations(dic.items(), r=2):
common = set(l1) & set(l2)
print(f"{k1} and {k2} have {len(common)} equal values: {', '.join(common)}")
# key1 and key2 have 2 equal values: b, c
# key1 and key3 have 1 equal values: a
# key2 and key3 have 1 equal values: e

如果出于某种原因你不愿意使用itertools:

for i, k1 in enumerate(dic):
for k2 in list(dic)[:i]:
common = set(dic[k1]) & set(dic[k2])
print(f"{k1} and {k2} have {len(common)} equal values: {', '.join(common)}")

最新更新