簡體   English   中英

查找數值最高的字典鍵

[英]Finding the dictionary keys whose values are numerically highest

給定以下形式的Python dict

dict = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258, ......}

是否有一種簡單的方法來打印具有最高數值的前x個鍵? 也就是說,說:

Beth   9102
Cecil  3258

目前,這是我的嘗試:

max = 0
max_word = ""
for key, value in w.word_counts.iteritems():
    if value > max:
        if key not in stop_words:
            max = value
            max_word = key

print max_word

我只需按第二個值對項目進行排序,然后選擇前K個元素:

d_items = sorted(d.items(), key=lambda x: -x[1])
print d_items[:2]
[('Beth', 9102), ('Cecil', 3258)]

這種方法的復雜度為O(N log N + K) ,與最佳O(N + K log K)沒什么不同(使用QuickSelect並僅對前K個元素進行排序)。

使用collections.Counter.most_common

>>> from collections import Counter
>>> d = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258}
>>> c = Counter(d)
>>> c.most_common(2)
[('Beth', 9102), ('Cecil', 3258)]

它采用sortedO(n*log n) ),或heapq.nlargest(k)可能是快於sorted ,如果k << nmax()如果k==1

>>> (sorted(dict.items(), key=lambda x:x[1]))[:2]
[('Alice', 2341), ('Cecil', 3258)]
items = sorted(w.word_counts.items(), lambda x, y: cmp(x[1], y[1]), None, True) 
items[:5]

將5替換為要獲取的元素數。

d = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258}

vs = sorted(d, key=d.get,reverse=True)

l = [(x,d.get(x)) for x in vs[0:2]]
n [4]: l
Out[4]: [('Beth', 9102), ('Cecil', 3258)]

dict轉換為元組[(2341, 'Alice'), ...]然后對其進行排序(不使用key=lambda ... )。

暫無
暫無

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

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