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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值