我有一本字典。使用python进行字典操作
dict = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
什么是简单的方法从字典的键找出相似的值?
output :
A&B : 'a', 'b'
A&C : None
B&C : 'c'
这是如何实现的?
我有一本字典。使用python进行字典操作
dict = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], }
什么是简单的方法从字典的键找出相似的值?
output :
A&B : 'a', 'b'
A&C : None
B&C : 'c'
这是如何实现的?
使用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'}
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'}
随着你的清单内容是哈希的,例如尝试'设置(字典[ 'A'])。交叉点(字典[ 'B'])'。不过,你不应该调用你自己的对象'dict'。 – jonrsharpe