按列表中出现的频率对列表进行排序 [英] Sorting a List by frequency of occurrence in a list
本文介绍了按列表中出现的频率对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数列表(或者甚至可以是字符串),我想按Python中出现的频率排序,例如:
I have a list of integers(or could be even strings), which I would like to sort by the frequency of occurrences in Python, for instance:
a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
元素5
在列表中出现4次,4
在列表中出现3次.因此,输出的排序列表将是:
Here the element 5
appears 4 times in the list, 4
appears 3 times. So the output sorted list would be :
result = [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
我尝试使用a.count()
,但是它给出了元素出现的次数.
我想对它进行排序.知道怎么做吗?
I tried using a.count()
, but it gives the number of occurrence of the element.
I would like to sort it. Any idea how to do it ?
谢谢
推荐答案
from collections import Counter
print [item for items, c in Counter(a).most_common() for item in [items] * c]
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
甚至更好(高效)的实施方式
Or even better (efficient) implementation
from collections import Counter
from itertools import repeat, chain
print list(chain.from_iterable(repeat(i, c) for i,c in Counter(a).most_common()))
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
或
from collections import Counter
print sorted(a, key=Counter(a).get, reverse=True)
# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
如果您喜欢就地排序
a.sort(key=Counter(a).get, reverse=True)
这篇关于按列表中出现的频率对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文