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

后端 未结 5 2007
别那么骄傲
别那么骄傲 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:38

    Why would you choose an O(n**2) algorithm to do this. The alternative to Counter (if you have <2.7) is not too difficult

    >>> from operator import itemgetter
    >>> from collections import defaultdict
    >>> L=[3, 3, 3, 4, 4, 2]
    >>> D=defaultdict(int)
    >>> for i in L:
    ...     D[i]+=1
    ... 
    >>> sorted(D.items(), key=itemgetter(1), reverse=True)
    [(3, 3), (4, 2), (2, 1)]
    

提交回复
热议问题