日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python字典统计排序1_python-如何按字典顺序对Counter.mostCommon(n)的...

發布時間:2025/3/12 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。