按频率排序列表

按频率排序列表

问题描述:

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)