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

将会:

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

输出应先按最高计数排序到最低计数。在这种情况下,3比2比1。

4

5 回答 5

13

您可以在 Python 2.7+中使用Counter (此配方适用于 2.5+):

from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]
于 2011-01-25T09:18:27.137 回答
3
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)]
于 2011-01-25T09:15:26.603 回答
2

为什么要选择 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)]
于 2011-01-25T10:16:08.247 回答
2

尝试使用 collections.Counter:

from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()
于 2011-01-25T09:19:19.967 回答
0
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 的参数不可用

于 2011-01-25T09:13:29.287 回答