在字典中的多个集合中查找相等的值
Find equal values among multiple collections within dictionary
我有字典:
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)}")
我有字典:
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)}")