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

雨燕双飞 提交于 2019-12-01 21:13:15

问题


[3, 3, 3, 4, 4, 2]

Would be:

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

The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1.


回答1:


data = [3, 3, 3, 4, 4, 2]
result = []
for entry in set(data):
    result.append((entry, data.count(entry)))
result.sort(key = lambda x: -x[1])
print result

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



回答2:


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)]



回答3:


Try using a collections.Counter:

from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()



回答4:


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)]



回答5:


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



来源:https://stackoverflow.com/questions/4791599/in-python-how-do-i-take-the-highest-occurrence-of-something-in-a-list-and-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!