简体   繁体   English

计算出现次数

[英]Count number of occurrences

I have the following list of numbers: 我有以下数字列表:

l = [2L, 14L, 14L, 14L, 11L, 2L, 2L, 11L, 14L, 11L, 14L, 2L, 2L, 14L, ...]

How would I find out the number of occurrences of a number (eg, 2 ) or of multiple numbers (eg, 2 or 5 or 7 )? 我如何找出数字(例如2 )或多个数字(例如257 )的出现次数?

The way I was going to do it was with a for loop, but I'm sure there's a more efficient way. 我要做的方式是使用for循环,但我确信这是一种更有效的方法。

collections.Counter makes a dictionary that maps values to the number of times they occur: collections.Counter创建一个字典,将值映射到它们出现的次数:

>>> from collections import Counter
>>> l = [2L, 14L, 14L, 14L, 11L, 2L, 2L, 11L, 14L, 11L, 14L, 2L, 2L, 14L]
>>> c = Counter(l)
>>> c
    Counter({14L: 6, 2L: 5, 11L: 3})
>>> c[14L]
    6
>>> l.count(2)
5

Simple as pie. 简单如馅饼。 If you have a list of numbers for which you would like to find counts you could try, for instance: 如果您有可以尝试的数字列表,您可以尝试,例如:

>>> {n: l.count(n) for n in [2, 5, 7]}
{2: 5, 5: 0, 7: 0}

If you want counts for all elements, I would suggest collections.Counter , as mentioned in the other answer. 如果你想要所有元素的计数,我会建议collections.Counter ,如另一个答案所述。

Collections.Counter was introduced in py2.7, so for py 2.6 and earlier you can try something like this: Collections.Counter是在py2.7中引入的,所以对于py 2.6及更早版本,你可以尝试这样的东西:

In [1]: l = [2L, 14L, 14L, 14L, 11L, 2L, 2L, 11L, 14L, 11L, 14L, 2L, 2L, 14L]

In [2]: dic={}

In [3]: for x in l:
   ...:     dic[x]=dic.get(x,0)+1
   ...:     

In [4]: dic
Out[4]: {2L: 5, 11L: 3, 14L: 6}

or use defaultdict (introduced in py2.5): 或使用defaultdict (在py2.5中引入):

In [6]: from collections import defaultdict

In [7]: dic=defaultdict(int)

In [8]: for x in l:
    dic[x]+=1
   ...:     

In [9]: dic
Out[9]: defaultdict(<type 'int'>, {2L: 5, 11L: 3, 14L: 6})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM