按列表中出现的频率对列表进行排序

Kir*_*ran 14 python sorting list

我有一个整数列表(或者甚至可以是字符串),我想根据Python中出现的频率对其进行排序,例如:

a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Run Code Online (Sandbox Code Playgroud)

这里元素5在列表中出现4次,4出现3次.所以输出排序列表将是:

result = [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
Run Code Online (Sandbox Code Playgroud)

我尝试过使用a.count(),但它给出了元素的出现次数.我想对它进行排序.知道怎么做吗?

谢谢

the*_*eye 26

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]
Run Code Online (Sandbox Code Playgroud)

甚至更好(有效)的实施

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]
Run Code Online (Sandbox Code Playgroud)

要么

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]
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢就地排序

a.sort(key=Counter(a).get, reverse=True)
Run Code Online (Sandbox Code Playgroud)


the*_*ner 6

使用 Python 3.3 和内置的sorted函数,以计数为键:

>>> a = [1,1,2,3,3,3,4,4,4,5,5,5,5]
>>> sorted(a,key=a.count)
[2, 1, 1, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
>>> sorted(a,key=a.count,reverse=True)
[5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]
Run Code Online (Sandbox Code Playgroud)

  • @thefourtheye,我必须计时才能确定,但​​这听起来不错。不可否认,这对于像示例这样的小列表来说非常安全。 (2认同)