简体   繁体   中英

Count multiple occurrences in a set list

Is there a way to count the amount occurrences of a set of string lists?

For example, when I have this list, it counts 7 ' ' blanks.

list = [[' ', ' ', ' ', ' ', ' ', ' ', ' ']]
print(list.count(' '))

Is there a way I can do this same thing but for a set of multiple lists? Like this for example below:

set = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], 
       [' ', ' ', ' ', ' ', ' ', ' ', ' '], 
       [' ', ' ', ' ', ' ', ' ', ' ', ' ']]
print(set.count(' '))

When I do it this same way, the output I get is 0 and not the actual count of occurrences.

Solution

This works:

>>> data = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], 
            [' ', ' ', ' ', ' ', ' ', ' ', ' '], 
            [' ', ' ', ' ', ' ', ' ', ' ', ' ']]
>>> sum(x.count(' ') for x in data)
21

You need to count in each sub list. I use a generator expression to do this and sum the results from all sub lists. BTW, don't use set as a variable name. It is a built-in.

Performance

While not that important for many cases, performance can be interesting:

%timeit sum(x.count(' ') for x in data)
1000000 loops, best of 3: 1.28 µs per loop

vs.

%timeit sum(1 for i in chain.from_iterable(data) if i==' ')
100000 loops, best of 3: 4.79 µs per loop

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