0

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

Toby Smith
  • 1,505
  • 2
  • 15
  • 24

1 Answers1

4

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')
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
  • 1
    -1 for `reduce`, +1 for `x.count('1') for x in xs`. Why would you use `O(n**2)` `reduce` that btw is available only from `functools` in Python 3 if you have `sum(x.count('1') for x in xs)`? – jfs Apr 26 '14 at 01:38
  • Yeah, actually the `sum()` one was at the top first but for some reason I felt flattening was simpler; I'll change it back. – Erik Kaplun Apr 26 '14 at 01:40
  • `chain(*xs)` should still be O(n). – Erik Kaplun Apr 26 '14 at 01:42
  • `chain(*xs)` is ok. It could be written as `chain.from_iterable(xs)` (not essential). The point is `reduce` is *less readable* and less efficient. I don't care if a *readable* solution is not the fastest one until a profiler says it is a bottleneck in my application. – jfs Apr 26 '14 at 01:46
  • You're right; I started out thinking `flatten` is easy to understand but of course not when it's done via `reduce`. – Erik Kaplun Apr 26 '14 at 01:48