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

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

    def myfun(x,y):
        return x[1]-y[1]
    
    list1 = [3, 3, 3, 4, 4, 2]
    s1 = set(list1)
    newlist = []
    for e in s1:
        newlist.append((e,list1.count(e)))
    print sorted(newlist,cmp=myfun)
    

    I think, this is what you asked for. Sorry for hurry with the first answer. But just note that cmp argument for sorted is not available in python3

提交回复
热议问题