2016-02-02 23 views

回答

6

簡單,使用的setintersection方法:

>>> set.intersection(*D.values()) 
{2} 

D.values()將返回你它們已經將字典值的列表,然後*D.values()會解開這個列表並將它傳遞給set

intersection方法
+0

你打我給它 –

+0

這是一種榮譽... :P .. –

+0

謝謝你@鐵拳 – Yousuf

0

如果您只是在每個字典中查找常用值,而不是查找每個字典中的值,那麼以下代碼將起作用!並不是說這是最快或最好的方法,但它的工作原理! 返回嵌入式字典中所有重複值的列表!

def findCommon(data): 

    flipped = {} 
    out = [] 

    for i in data: 
     for value in data[i]: 
      if value not in flipped: 
       flipped[value] = [i] 
      else: 
       flipped[value].append(i) 
    for i in flipped: 
     if len(flipped[i]) > 1: 
      out.append(i) 
    return out 
+0

如果你想自己解決它! – TheLazyScripter

3

對於各種各樣的原因,你也可以使用reduce()

>>> D = {'A': {1, 2, 3}, 'B': {2 ,4, 5}, 'C': {1, 2, 7}} 
>>> reduce(lambda x, y: x & y, D.values()) # or use operator.and_ instead of lambda 
{2} 

reduce()是在Python 2.x的內置功能,但需要從Python中functools模塊進口3.x的

+0

Python3 +中的'reduce'是否可用? –

+1

@Iron Fist:在Python 3.x中,您需要說'from functools import reduce'。 –

0

如果用reduce去的最有效的方法是使用operator.and_

from functools import reduce 
from operator import and_ 

D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}} 

print(reduce(and_, D.values())) 

set.intersection將是很難被擊敗:

In [89]: from functools import reduce 

In [90]: from operator import and_ 

In [91]: timeit reduce(lambda x, y: x & y, D.values()) 
1000 loops, best of 3: 221 µs per loop 

In [92]: timeit reduce(and_,D. values()) 
10000 loops, best of 3: 170 µs per loop 

In [93]: timeit set.intersection(*D.values()) 
10000 loops, best of 3: 155 µs per loop