欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2025/3/12 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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)的...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。