给定dict形式的Python :
dict = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258, ......}
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来打印具有最高数值的前x个键?也就是说:
Beth 9102
Cecil 3258
Run Code Online (Sandbox Code Playgroud)
目前这是我的尝试:
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
Run Code Online (Sandbox Code Playgroud)
我只是按第二个值对项目进行排序,然后选择前K个元素:
d_items = sorted(d.items(), key=lambda x: -x[1])
print d_items[:2]
[('Beth', 9102), ('Cecil', 3258)]
Run Code Online (Sandbox Code Playgroud)
这种方法的复杂性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)]
Run Code Online (Sandbox Code Playgroud)
它采用sorted(O(n*log n)),或者heapq.nlargest(k)可能是比快sorted,如果k << n,或max()如果 k==1.