說,我有一本字典D
:如何從Python字典值中查找常用項目?
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
現在我想有從D
的價值觀,這將是2 我試圖用set.intersection
,但它沒有工作,所有的普通物品。
說,我有一本字典D
:如何從Python字典值中查找常用項目?
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
現在我想有從D
的價值觀,這將是2 我試圖用set.intersection
,但它沒有工作,所有的普通物品。
簡單,使用的set
intersection
方法:
>>> set.intersection(*D.values())
{2}
D.values()
將返回你它們已經將字典值的列表,然後*D.values()
會解開這個列表並將它傳遞給set
類
intersection
方法
如果您只是在每個字典中查找常用值,而不是查找每個字典中的值,那麼以下代碼將起作用!並不是說這是最快或最好的方法,但它的工作原理! 返回嵌入式字典中所有重複值的列表!
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
如果你想自己解決它! – TheLazyScripter
對於各種各樣的原因,你也可以使用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}
Python3 +中的'reduce'是否可用? –
@Iron Fist:在Python 3.x中,您需要說'from functools import reduce'。 –
如果用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
你打我給它 –
這是一種榮譽... :P .. –
謝謝你@鐵拳 – Yousuf