Python:如何获取列表中项目的排序数量?

AP2*_*257 9 python

在Python中,我有一个项目列表,如:

mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]
Run Code Online (Sandbox Code Playgroud)

我想输出如下内容:

a (4)
b (3)
d (3)
c (2)
e (1)
Run Code Online (Sandbox Code Playgroud)

如何输出列表中项目的计数和排行榜?我不太关心效率,只是任何方式工作:)

谢谢!

Eli*_*ght 7

from collections import defaultdict

def leaders(xs, top=10):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]
Run Code Online (Sandbox Code Playgroud)

因此,此函数使用a defaultdict来计算列表中每个条目的数量.然后我们取每对条目及其计数,并根据计数按降序排序.然后我们获取top条目数并返回.

所以现在我们可以说

>>> xs = list("jkl;fpfmklmcvuioqwerklmwqpmksdvjioh0-45mkofwk903rmiok0fmdfjsd")
>>> print leaders(xs)
[('k', 7), ('m', 7), ('f', 5), ('o', 4), ('0', 3), ('d', 3), ('i', 3), ('j', 3), ('l', 3), ('w', 3)]
Run Code Online (Sandbox Code Playgroud)


AXO*_*AXO 6

我很惊讶没有人提到collections.Counter。假设

import collections
mylist = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'd', 'd', 'd', 'c', 'c', 'e']
Run Code Online (Sandbox Code Playgroud)

这只是一个班轮:

print(collections.Counter(mylist).most_common())
Run Code Online (Sandbox Code Playgroud)

这将打印:

[('a', 4), ('b', 3), ('d', 3), ('c', 2), ('e', 1)]
Run Code Online (Sandbox Code Playgroud)

请注意,它Counterdict具有一些用于计数对象的有用方法的子类。有关更多信息,请参阅文档


Ott*_*ger 5

双线:

for count, elem in sorted(((mylist.count(e), e) for e in set(mylist)), reverse=True):
    print '%s (%d)' % (elem, count)
Run Code Online (Sandbox Code Playgroud)