计数器:订购具有相同计数的元素

时间:2017-10-26 15:08:47

标签: python python-3.x collections

文档指定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)]

所需结果(适用于arr2arr2):

[(1, 3), (3, 3), (2, 2), (5, 1)]

1 个答案:

答案 0 :(得分:4)

只需对其进行适当排序:

sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))