Sort list by frequency

后端 未结 7 1203
孤城傲影
孤城傲影 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:49

    I think this would be a good job for a collections.Counter:

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

    Alternatively, you could write the second line without a lambda:

    counts = collections.Counter(lst)
    new_list = sorted(lst, key=counts.get, reverse=True)
    

    If you have multiple elements with the same frequency and you care that those remain grouped, we can do that by changing our sort key to include not only the counts, but also the value:

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

提交回复
热议问题