Python:如何获得列表中项目的排序计数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2290962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: how to get sorted count of items in a list?
提问by AP257
In Python, I've got a list of items like:
在 Python 中,我有一个项目列表,例如:
mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]
And I'd like to output something like:
我想输出如下内容:
a (4)
b (3)
d (3)
c (2)
e (1)
How can I output a count and leaderboard of items in a list? I'm not too bothered about efficiency, just any way that works :)
如何输出列表中项目的计数和排行榜?我不太关心效率,只是任何有效的方式:)
Thanks!
谢谢!
采纳答案by Eli Courtwright
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]
So this function uses a defaultdict
to count the number of each entry in our list. We then take each pair of the entry and its count and sort it in descending order according to the count. We then take the top
number of entries and return that.
所以这个函数使用 adefaultdict
来计算我们列表中每个条目的数量。然后我们取出每对条目及其计数,并根据计数将其按降序排序。然后我们获取top
条目的数量并返回它。
So now we can say
所以现在我们可以说
>>> 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)]
回答by AXO
I'm surprised that no one has mentioned collections.Counter
. Assuming
我很惊讶没有人提到collections.Counter
。假设
import collections
mylist = ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'd', 'd', 'd', 'c', 'c', 'e']
it's just a one liner:
这只是一个班轮:
print(collections.Counter(mylist).most_common())
which will print:
这将打印:
[('a', 4), ('b', 3), ('d', 3), ('c', 2), ('e', 1)]
Note that Counter
is a subclass of dict
with some useful methods for counting objects. Refer to the documentationfor more info.
请注意,它Counter
是dict
具有一些用于计数对象的有用方法的子类。有关更多信息,请参阅文档。
回答by Otto Allmendinger
A two-liner:
两线:
for count, elem in sorted(((mylist.count(e), e) for e in set(mylist)), reverse=True):
print '%s (%d)' % (elem, count)