按频率排序列表 [英] Sort list by frequency

查看:72
本文介绍了按频率排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中有什么方法可以按频率对列表进行排序?

Is there any way in Python, wherein I can sort a list by its frequency?

例如

[1,2,3,4,3,3,3,6,7,1,1,9,3,2]

上面的列表将按照其值的频率顺序进行排序,以创建以下列表,其中频率最高的项放在前面:

the above list would be sorted in the order of the frequency of its values to create the following list, where the item with the greatest frequency is placed at the front:

[3,3,3,3,3,1,1,1,2,2,4,6,7,9]

推荐答案

我认为这对于collections.Counter来说是一件好事:

I think this would be a good job for a collections.Counter:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])


或者,您也可以写第二行而不使用lambda:


Alternatively, you could write the second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)

如果您有多个具有相同频率的元素,并且您希望它们保持分组状态,我们可以通过更改排序键以不仅包括计数而且还包括值来做到这一点:

If you have multiple elements with the same frequency and you care that those remain grouped, we can do that by changing our sort key to include not only the counts, but also the value:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: (counts[x], x), reverse=True)

这篇关于按频率排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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