sorting a python list by frequency of elements

自作多情 提交于 2021-01-29 03:42:36

问题


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 [3,1,2,2,4] the output should be [1,3,4,2,2] but I get [3,1,4,2,2]. How do I resolve this error?


回答1:


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))



回答2:


You are only sorting by the number of item. Under this logic, all the items which appear once have the same "weight", so python retains their original relevant position. E.g., 3 and 1 both appear once, so as far as their sorting is concerned, they are equivalent. Since 3 comes before 1 in the original list, it is also placed first in the result.

Your required output calls for a secondary sort criteria - the value of the element. To do so, you must specify this explicitly:

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


来源:https://stackoverflow.com/questions/38821352/sorting-a-python-list-by-frequency-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!