2013-10-21 53 views
3

如何在給定每個元素的頻率的字典中返回最常出現的元素?例如,在下面的列表中,我想要返回第一頻率出現頻率最高的元素,第二頻率出現頻率最高的元素?在python字典中獲取頻率最高的項目給定頻率

dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] } 

因此該方法findMostFreqFirst(dictionary)將返回「第一」和方法findMostFreqSecond將返回「第三」。有沒有辦法使用最有效的代碼量來做到這一點? (我與key關鍵字參數寫這作爲一個更大計劃的一部分,所以我不想寫的代碼量豐富這兩個功能感謝

+1

不應該'findMostFreqSecond'回報'「第三」'? –

+0

哦,是的,更新的問題。 –

回答

6

使用max:!

>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] } 
>>> max(dictionary, key=lambda key: dictionary[key][0]) 
'first' 
>>> max(dictionary, key=lambda key: dictionary[key][1]) 
'third' 
因爲列表比較的字典順序進行

第一個可以寫成如下。([30, 40] > [20, 50]

>>> max(dictionary, key=dictionary.get) 
'first' 
+2

我會做'max(dictionary.keys()'......不知道你可以只做'max(字典)'謝謝! –

0

您可以用這種方式的一次。

第一個元素:

>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] } 
>>> sorted(dictionary, key=lambda key: dictionary[key][0], reverse=True) 
['first', 'third', 'second'] 

然後使用索引來排序列表中的問題返回元素:

>>> sorted(dictionary, key=lambda key: dictionary[key][0], reverse=True)[0] 
'first' 

第二個元素:

>>> sorted(dictionary, key=lambda key: dictionary[key][1], reverse=True) 
['third', 'first', 'second'] 

如果你想第二個元素打破與第一個並列:

>>> dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50], 
...    "fourth":[30,60]} 
>>> sorted(dictionary, key=lambda key: dictionary[key][0:2], reverse=True) 
['fourth', 'first', 'third', 'second'] 
+0

@JonClements:怎麼這樣? – dawg

+0

@falsetru:修正了 – dawg

+0

它現在做(雖然效率不高) - 我原來的評論是在你的第一篇文章後的一分鐘:) –

0

有點晚表,但可以辦理「列」具有不同長度任意數量的將是一個辦法:

dictionary = {"first": [30, 40], "second": [10, 30], "third": [20, 50] } 

from itertools import izip_longest 

keys, vals = zip(*dictionary.items()) 
items = izip_longest(*vals, fillvalue=0) 
print [keys[max(xrange(len(item)), key=item.__getitem__)] for item in items] 
# ['first', 'third'] 
+0

謝謝,這絕對有用 –