a_list.count(a_callable) ?
Carsten Haese
carsten at uniqsys.com
Thu Jun 14 17:34:37 EDT 2007
On Thu, 2007-06-14 at 12:53 -0700, Ping wrote:
> Hi,
>
> I'm wondering if it is useful to extend the count() method of a list
> to accept a callable object? What it does should be quite intuitive:
> count the number of items that the callable returns True or anything
> logically equivalent (non-empty sequence, non-zero number, etc).
>
> This would return the same result as len(filter(a_callable, a_list)),
> but without constructing an intermediate list which is thrown away
> after len() is done.
>
> This would also be equivalent to
> n = 0
> for i in a_list:
> if a_callable(i): n += 1
> but with much shorter and easier-to-read code. It would also run
> faster.
As an alternative to the generator-sum approach I posted in reply to
Dustan's suggestion, you could (ab)use the fact that count() uses
equality testing and do something like this:
>>> class Oddness(object):
... def __eq__(self, other): return other%2==1
...
>>> [1,2,3,4,5].count(Oddness())
3
I don't know which approach is faster. Feel free to compare the two.
HTH,
--
Carsten Haese
http://informixdb.sourceforge.net
More information about the Python-list
mailing list