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

新手上路,请多包涵

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

 a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]

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

 result = [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]

我尝试使用 a.count() ,但它给出了元素出现的次数。我想整理一下。知道怎么做吗?

谢谢

原文由 Kiran 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 610
2 个回答
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]

甚至更好(高效)的实施

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)

原文由 thefourtheye 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 >>> 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]

原文由 thegrinner 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题