简体   繁体   中英

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 )?

The way I was going to do it was with a for loop, but I'm sure there's a more efficient way.

collections.Counter makes a dictionary that maps values to the number of times they occur:

>>> 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 was introduced in py2.7, so for py 2.6 and earlier you can try something like this:

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):

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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