Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by frequency

Is there any way in Python, wherein I can sort a list by its frequency?

For example,

[1,2,3,4,3,3,3,6,7,1,1,9,3,2]

the above list would be sorted in the order of the frequency of its values to create the following list, where the item with the greatest frequency is placed at the front:

[3,3,3,3,3,1,1,1,2,2,4,6,7,9]
like image 913
user2592835 Avatar asked Sep 12 '14 19:09

user2592835


3 Answers

I think this would be a good job for a collections.Counter:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])

Alternatively, you could write the second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)

If you have multiple elements with the same frequency and you care that those remain grouped, we can do that by changing our sort key to include not only the counts, but also the value:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: (counts[x], x), reverse=True)
like image 98
mgilson Avatar answered Oct 21 '22 10:10

mgilson


l = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]
print sorted(l,key=l.count,reverse=True)

[3, 3, 3, 3, 3, 1, 1, 1, 2, 2, 4, 6, 7, 9]
like image 39
Padraic Cunningham Avatar answered Oct 21 '22 08:10

Padraic Cunningham


You can use a Counter to get the count of each item, use its most_common method to get it in sorted order, then use a list comprehension to expand again

>>> lst = [1,2,3,4,3,3,3,6,7,1,1,9,3,2]
>>> 
>>> from collections import Counter
>>> [n for n,count in Counter(lst).most_common() for i in range(count)]
[3, 3, 3, 3, 3, 1, 1, 1, 2, 2, 4, 6, 7, 9]
like image 2
Sunitha Avatar answered Oct 21 '22 10:10

Sunitha