a_list.count(a_callable) ?
BJörn Lindqvist
bjourne at gmail.com
Fri Jun 15 14:06:00 EDT 2007
On 6/15/07, Ping <ping.nsr.yeh 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.
>
> I would still prefer an expression like a_list.count(a_callable),
> which is short, clean, and easy to understand. :) However,
> it does produce ambiguities if a_list is a list of callables.
> Should the count() method match values or check return values
> of a_callable? There are several possible designs but I'm not
> sure which is better.
Maybe you could extend count() analogous to how sort() works:
# L is a list of Person objects, each Person has a name attribute
L.sort(key = attrgetter("name"))
# How many olle are there?
print L.count("olle", key = attrgetter("name"))
# And index could be extended in the same way!
# Whom has id 1234?
print L.index(1234, key = attrgetter("id")).name
All of these could be solved by giving Person an __eq__() method, but
it fails when you need to search, sort or count on a different key.
--
mvh Björn
More information about the Python-list
mailing list