的一種方式,但長期的字典沒有更有效的使用itertools.combinations
找到你的字典,然後在組合循環,然後套之間的組合拿到項目集合之間的交集:
one = {'one':{'A':'m','B':'n','C':'o'}}
two ={'two':{'A':'m','B':'n','C':'p'}}
three = {'three':{'A':'x','B':'n','C':'p'}}
dict_list=[one,two,three]
v_item=[i.items() for i in dict_list]
from itertools import combinations
names=[]
items=[]
l=[combinations(v_item,i) for i in range(2,4)]
flat=[[[t[0] for t in k] for k in j] for j in l]
"""this line is for flattening the combinations i don't know why but python puts every elements within a list :
>>> l
[[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})]),
([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})]),
([('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])],
[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])]]"""
for comb in flat :
for pair in comb:
names,items =zip(*pair)
items=[i.viewitems() for i in items]
print names,reduce(lambda x,y:x&y,items)
結果:
('one', 'two') set([('B', 'n'), ('A', 'm')])
('one', 'three') set([('B', 'n')])
('two', 'three') set([('B', 'n'), ('C', 'p')])
('one', 'two', 'three') set([('B', 'n')])
個
約在下面幾行:
items=[i.viewitems() for i in items]
print names,reduce(lambda x,y:x&y,items)
您需要到C reate a view
object of your items踹如set
對象,那麼你可以計算出項目的交叉口&
操作。 使用reduce
函數。
UFF,你是對的,這是對大數據集慘遭緩慢,加上運行內存:O:/ –