文档指定 collections.Counter.most_common()
,
elements with equal counts are ordered arbitrarily.
我对一种简洁的方式很感兴趣,它首先按频率/值降序(默认)排序,然后再按键升序排序。 (键只是 .most_common()
中每个元组的第 0 个元素。)
例子:
from collections import Counter
arr1 = [1, 1, 1, 2, 2, 3, 3, 3, 5]
arr2 = [3, 3, 3, 1, 1, 1, 2, 2, 5] # Same values, different order
print(Counter(arr1).most_common())
print(Counter(arr2).most_common())
# [(1, 3), (3, 3), (2, 2), (5, 1)]
# [(3, 3), (1, 3), (2, 2), (5, 1)]
期望的结果(对于 arr2
和 arr2
):
[(1, 3), (3, 3), (2, 2), (5, 1)]
最佳答案
适当排序即可:
sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))
关于python - 计数器 : ordering elements with equal counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957889/