Sort list by frequency
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)
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]