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]
Was practising this one for fun. This solution use less time complexity.
I think this would be a good job for a
collections.Counter
:Alternatively, you could write the second line without a lambda:
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:
You can use below methods. It is written in simple python.