The docs specify that for collections.Counter.most_common(),
elements with equal counts are ordered arbitrarily.
I'm interested in a concise way to order first by frequency/value descending (the default), but then secondarily by key, ascending. (Key is just the 0th element of each tuple from .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)]
Desired result (for both arr2 and arr2):
[(1, 3), (3, 3), (2, 2), (5, 1)]
Just sort it appropriately:
sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With