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

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -