Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter: ordering elements with equal counts

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)]
like image 723
Brad Solomon Avatar asked Apr 12 '26 03:04

Brad Solomon


1 Answers

Just sort it appropriately:

sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))
like image 86
user2390182 Avatar answered Apr 13 '26 15:04

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!