Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how do I take the highest occurrence of something in a list, and sort it that way?

[3, 3, 3, 4, 4, 2]

Would be:

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

The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1.

like image 471
TIMEX Avatar asked Nov 30 '22 09:11

TIMEX


1 Answers

You can use a Counter in Python 2.7+ (this recipe works on 2.5+):

from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]
like image 58
TryPyPy Avatar answered Dec 05 '22 19:12

TryPyPy