Reputation: 51
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.
Upvotes: 2
Views: 1094
Reputation: 85612
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.
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
Upvotes: 6