counting occurances in lists within lists.

Peter Hansen peter at engcorp.com
Sat Dec 21 13:43:26 EST 2002


Adonis wrote:
> "Adonis" <deltapigz at telocity.com> wrote:
> > how do i effectively count the amount of 0s in what is mentioned on the
> > subject.
> > [[0,0,0,1,2,3]
> >  [4,5,6,7,8,9]
> >  [10,11,12,13,14,15]]
> >
> > return 3 0s found.
> >
> nevermind got it. im an idiot.

It's always nice to get the answer yourself... but this is 
comp.lang.python so a long thread with variations on the theme
is mandatory.

In older Pythons, you might do this:

L = [[0,0,0,1,2,3], [4,5,6,7,8,9], [10,11,12,13,14,15]]
import operator
reduce(operator.add, map(lambda x: x.count(0), L))

In newer ones, maybe use a list comprehension in place of the map
and lambda, but I'm not sure how to avoid the reduce with a list
comprehension or other approach.  Maybe someone else can advise:

reduce(operator.add, [x.count(0) for x in L])

-Peter



More information about the Python-list mailing list