按频率对计数器排序,然后在Python中按字母顺序排序 [英] Sort Counter by frequency, then alphabetically in Python

查看:181
本文介绍了按频率对计数器排序,然后在Python中按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用计数器按出现的顺序对字母进行排序,并将具有相同频率的任何字母按字母顺序排列,但是我无法访问它所产生的字典的Value.

I am trying to use counter to sort letters by occurrence, and put any that have the same frequency into alphabetical order, but I can't get access to the Value of the dictionary that it produces.

letter_count = collections.Counter("alphabet")
print(letter_count)

产生:

Counter({'a': 2, 'l': 1, 't': 1, 'p': 1, 'h': 1, 'e': 1, 'b': 1})

如何使它按频率排序,然后按字母顺序排序,所以仅显示一次的所有内容都是按字母顺序排序?

How can I get it ordered by frequency, then by alphabetical order, so everything that shows up only once is in alphabetical order?

推荐答案

听起来您的问题是如何按频率对整个列表进行排序,然后按字母顺序断开关系.您可以像这样对整个列表进行排序:

It sounds like your question is how to sort the entire list by frequency, then break ties alphabetically. You can sort the entire list like this:

>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0]))
>>> print(a)
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]

如果您希望输出仍然是字典,则可以将其转换为

If you want the output to be a dict still, you can convert it into a collections.OrderedDict:

>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
#              ('b', 1),
#              ('e', 1),
#              ('h', 1),
#              ('l', 1),
#              ('p', 1),
#              ('t', 1)])

这将保留顺序,如您所见.首先使用'a'是因为它最常见.其他所有内容均按字母顺序排序.

This preserves the ordering, as you can see. 'a' is first because it's most frequent. Everything else is sorted alphabetically.

这篇关于按频率对计数器排序,然后在Python中按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆