Sort list by frequency

后端 未结 7 1190
孤城傲影
孤城傲影 2020-11-27 07:23

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

7条回答
  •  鱼传尺愫
    2020-11-27 07:42

    In case you want to use a double comparator.

    For example: Sort the list by frequency in descending order and in case of a clash the smaller one comes first.

    import collections 
    
    def frequency_sort(a):
        f = collections.Counter(a)
        a.sort(key = lambda x:(-f[x], x))
        return a
    

提交回复
热议问题