In python, how do I take the highest occurrence of something in a list, and sort it that way?

后端 未结 5 1959
别那么骄傲
别那么骄傲 2021-01-19 06:20
[3, 3, 3, 4, 4, 2]

Would be:

[ (3, 3), (4, 2), (2, 1) ]

The output should be sorted by highest count first to low

5条回答
  •  孤城傲影
    2021-01-19 06:34

    You can use a Counter in Python 2.7+ (this recipe works on 2.5+):

    from collections import Counter
    print Counter([3, 3, 3, 4, 4, 2]).most_common()
    # [(3, 3), (4, 2), (2, 1)]
    

提交回复
热议问题