sorting a python list by frequency of elements -


i have code sorts python list frequency of elements. works other cases except when frequency of 2 elements same. if frequency same want place smaller value first before higher value:

counts = collections.counter(arr) new_list = sorted(arr, key=lambda x: counts[x])  item in new_list:     print item 

in case of [3,1,2,2,4] output should [1,3,4,2,2] [3,1,4,2,2]. how resolve error?

you can set key lambda function tuple, so, sort counts[x] first , if there tie, sort x, value itself.

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

Comments

Popular posts from this blog

PHP while loop dynamic rowspan -

timer - Java TimerTask cancel -

android - How to read a column value in parse.com without accessing an object or a pointer -