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

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

Will be:

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

The output should be sorted by the highest score from the first to the lowest value. In this case, from 3 to 2.

+4
python list list-manipulation
source share
5 answers
 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)] 
+3
source share

You can use 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)] 
+13
source share

Try using collections. Content:

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

Why would you choose the O (n ** 2) algorithm for this. An alternative to a counter (if you have <2.7) is not too complicated

 >>> 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)] 
+2
source share
 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 to rush to the first answer. But just note that cmp argument for sorting is not available in python3

0
source share

All Articles