文档指定collections.Counter.most_common()
,
具有相同计数的元素是任意排序的。
我对以频率/值降序(默认值)排序的简洁方式感兴趣,但其次是按键,升序。 (Key只是来自.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)]
答案 0 :(得分:4)
只需对其进行适当排序:
sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))