我有一本字典。
dict = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
从字典键中找出相似值的简单方法是什么?
output :
A&B : 'a', 'b'
A&C : None
B&C : 'c'
如何实现这一目标?
答案 0 :(得分:9)
In [1]: dct = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
In [2]: set(dct['A']).intersection(dct['B'])
Out[2]: {'a', 'b'}
In [3]: set(dct['A']).intersection(dct['C'])
Out[3]: set()
In [4]: set(dct['B']).intersection(dct['C'])
Out[4]: {'c'}
答案 1 :(得分:2)
使用set & other_set
operator or set.intersection
和itertools.combinations
:
>>> import itertools
>>>
>>> d = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
>>> for a, b in itertools.combinations(d, 2):
... common = set(d[a]) & set(d[b])
... print('{}&{}: {}'.format(a, b, common))
...
A&C: set()
A&B: {'b', 'a'}
C&B: {'c'}