2012-03-26 70 views

回答

8

查看的文档set.intersection(),用于寻找序列中共同的元件它非常有用的,并且可以使用任一方法或语法a & b其中两个ab是集。

这里是做你想要什么简洁的方式:或使用reduce()

>>> set.intersection(*map(set, mydict.values())) 
set(['cat']) 

潜在的更具可读性的解决方案:

reduce(set.intersection, map(set, mydict.values())) 
1
>>> mydict = {'first': ['cat', 'dog'], 'second': ['fish', 'cat']} 
>>> from collections import Counter 
>>> c = Counter(i for v in mydict.values() for i in v) 
>>> print [i for i in c if c[i]==len(mydict)] 
['cat'] 
5
mydict = {'first': ['cat', 'dog'], 'second': ['fish', 'cat']} 
def similar(x,y):return [c for c in set(x).intersection(set(y))] 
reduce(similar, mydict.values()) 
1

只是另一种方式:

first = True 
for x in mydict: 
    if first: 
     common = set(mydict[x]) 
     first = False 
    else: 
     common = common & set(mydict[x]) 
print common 
1
l2=[x for x in mydict.values()] 
dic = {} 
for e in l2: 
    for i in e: 
     dic.setdefault(i,0) 
     dic[i]+=1 
for e in dic.items(): 
    if len(l2) == e[1]: 
     print e[0] # cat