这里的问题是Counter dict是无序的,并且most_common不在乎键.为此,您需要对字典中的项目进行排序,然后提取最常见的3个项目.
counter = Counter('abcdef')
most_common = sorted(counter.items(), key=lambda pair: (-pair[1], pair[0]))
这将首先对-pair [1](计数)进行排序.由于出现负数,较高的计数将首先出现.接下来,我们对对[0](键)进行排序,对将按字典顺序以正常的升序排序.
从这里,您需要切出想要的项目…
most_common[:3]
或者,我们可以从the source code中取出一个页面,然后重新实现most_common以考虑密钥.
import heapq as _heapq
def most_common(counter, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
sort_key = lambda pair: (-pair[1], pair[0])
if n is None:
return sorted(counter.iteritems(), key=sort_key)
return _heapq.nsmallest(n, counter.iteritems(), key=sort_key)