python字典统计排序1_python-如何按字典顺序对Counter.mostCommon(n)的...
這里的問題是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)
總結
以上是生活随笔為你收集整理的python字典统计排序1_python-如何按字典顺序对Counter.mostCommon(n)的...的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: memkind版本查看_QQ 20周年来
- 下一篇: servlet post 返回值是一个对
