a_list.count(a_callable) ?

Dustan DustanGroups at gmail.com
Fri Jun 15 17:17:24 EDT 2007


On Jun 15, 12:52 pm, Ping <ping.nsr.... at gmail.com> wrote:
> On 6 15 ,   11 17 , Dustan <DustanGro... at gmail.com> wrote:
>
>
>
> > On Jun 15, 9:15 am, Ping <ping.nsr.... at gmail.com> wrote:
>
> > > > sum(1 for i in a_list if a_callable(i))
>
> > > > --
> > > > Carsten Haesehttp://informixdb.sourceforge.net
>
> > > This works nicely but not very intuitive or readable to me.
>
> > > First of all, the generator expression makes sense only to
> > > trained eyes.  Secondly, using sum(1 ...) to mean count()
> > > isn't very intuitive either.
>
> > Then wrap it in a function:
> > def count(a_list, a_function):
> >    return sum(1 for i in a_list if a_function(i))
>
> > And call the function. You can also give it a different name (although
> > I can't think of a concise name that would express it any better).
>
> Hmm... This sounds like the best idea so far.  It is efficient both
> in memory and time while exposes an easy-to-understand name.
> I would name the function count_items though.
>
> n = count_items(a_list, lambda x: x > 3)     # very readable  :)

Although that particular example would be more efficient inlined,
because of the additional time spent creating the lambda function in
your count_items call.

sum(1 for i in a_list if i > 3)




More information about the Python-list mailing list