簡體   English   中英

在給定頻率的python詞典中獲取最頻繁的項目

[英]Get most frequent item in python dictionary given frequencies

在給定每個元素的頻率的情況下,如何返回字典中最常出現的元素? 例如,在下面的列表中,我想通過第一個頻率返回最頻繁出現的元素,並且通過第二個頻率返回最頻繁出現的元素?

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

因此方法findMostFreqFirst(dictionary)將返回“first”,方法findMostFreqSecond將返回“third”。 有沒有辦法可以使用最有效的代碼量來做到這一點? (我寫這篇文章是一個更大的程序的一部分,所以我不想為這兩個函數編寫大量的代碼。謝謝!

使用max with key keyword參數:

>>> 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'

你可以這樣做。

第一要素:

>>> 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']

該表稍晚,但是可以處理具有不同長度的任意數量的“列”的方法將是:

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'] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM