user2916886 user2916886 - 1 year ago 71
Python Question

sorting a python list by frequency of elements

I have this code which sorts python list by frequency of elements. It works for all other cases except when frequency of two elements are same. If the frequency is same then I want to place smaller value first before higher value:

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

for item in new_list:
print item

In case of
the output should be
but I get
. How do I resolve this error?

Answer Source

You can set your key lambda function to a tuple, so, It will sort by counts[x] first and if there is a tie, it will sort by x, the value itself.

 new_list = sorted(arr, key=lambda x: (counts[x], x))