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

Bra*_*mon 3 python collections python-3.x

该文档指定collections.Counter.most_common()

相等计数的元素是任意排序的。

我对一种简洁的方法感兴趣,该方法首先按频率/值降序(默认)排序,然后按键升序排序。(键只是。中每个元组的第0个元素.most_common()。)

例:

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

所需的结果(对于arr2arr2):

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

sch*_*ggl 7

只需对其进行适当排序:

sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))
Run Code Online (Sandbox Code Playgroud)