Вопрос

The .count() doesn't check lists within other lists. How can I?

FirstList = [ ['1', '2', '3'],
              ['4', '5', '6'],
              ['7', '8', '9'] ]

While

FirstList[0].count('1')

returns 1. I want to check all of FirstList. How can I do this???

Это было полезно?

Решение

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')
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top