[3, 3, 3, 4, 4, 2]
将会:
[ (3, 3), (4, 2), (2, 1) ]
输出应先按最高计数排序到最低计数。在这种情况下,3比2比1。
[3, 3, 3, 4, 4, 2]
将会:
[ (3, 3), (4, 2), (2, 1) ]
输出应先按最高计数排序到最低计数。在这种情况下,3比2比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)]
为什么要选择 O(n**2) 算法来执行此操作。Counter 的替代方案(如果你有 <2.7)并不太难
>>> 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)]
尝试使用 collections.Counter:
from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()
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)
我想,这就是你要求的。抱歉,第一个答案太匆忙了。但请注意,cmp
在 python3 中, sorted 的参数不可用