Here are 3 possible solutions:
given:
xs = [['1', '2', '3'],
['4', '1', '1'],
['7', '8', '1']]
[x.count('1') for x in xs]
will return
[1, 2, 1]
and if you want to reduce that to a single value, use sum
on that in turn:
sum(x.count('1') for x in xs)
which will, again, give you:
4
or, alternatively, you can flatten the nested list and just run count('1')
on that once:
reduce(lambda a, b: a + b, xs).count('1')
which will yield
4
but as J.F.Sebastian pointed out, this is less efficient/slower than the simple sum
solution.
or instead of reduce
, you can use itertools.chain
for the same effect (without the added computational complexity):
list(chain(*xs)).count('1')