该文档指定对于collections.Counter.most_common() https://docs.python.org/3.6/library/collections.html#collections.Counter,
具有相同计数的元素是任意排序的。
我对一种简洁的方式感兴趣,首先按频率/值降序(默认)排序,然后再按键升序排序。 (键只是每个元组的第 0 个元素.most_common()
.)
Example:
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
and arr2
):
[(1, 3), (3, 3), (2, 2), (5, 1)]