if does not evaluate

Peter Otten __peter__ at web.de
Fri Jun 11 03:06:32 EDT 2004


Jim Newton wrote:

> By the way, how do you find out in Python if there is
> a member of a list that matches a condition?  It is something
> i often and never know the best way to do it?  I can
> use a list compression to find ALL the matches, but what
> if i only want to know whether or not there is a match?

Generator expressions will solve that, I think

"Mary" in (person.name for person in people)

In the meantime:

>>> class Person:
...     def __init__(self, name):
...             self.name = name
...
>>> people = map(Person, "Jim Bob Mary Sue".split())
>>>
>>> def attrgetter(name):
...     return lambda o: getattr(o, name)
...
>>> import itertools
>>> "Mary" in itertools.imap(attrgetter("name"), people)
True

No big deal.

Peter




More information about the Python-list mailing list