[3, 3, 3, 4, 4, 2]
将是:
[ (3, 3), (4, 2), (2, 1) ]
输出应按最高计数从第一到最低计数排序。在这种情况下,3到2比1。
答案 0 :(得分:13)
您可以在Python 2.7+中使用Counter(this recipe适用于2.5 +):
from collections import Counter
print Counter([3, 3, 3, 4, 4, 2]).most_common()
# [(3, 3), (4, 2), (2, 1)]
答案 1 :(得分: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)]
答案 2 :(得分:2)
尝试使用collections.Counter:
from collections import Counter
data = [3,4,2,3,4,3]
Counter(data).most_common()
答案 3 :(得分: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)]
答案 4 :(得分: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)
我想,这就是你要求的。很抱歉第一个回答快点。但请注意,python3
中没有cmp
有关已排序的参数