if does not evaluate
Jim Newton
jimka at rdrop.com
Fri Jun 11 10:59:12 EDT 2004
so what i have done in the past is write a generic searching function.
def exists(predicate,seq):
for item in seq:
if( predicate(item)):
return True
return False
then i used that funcion in a test.
x = ["Peter", "Paul", "Mary", "Jane"]
if( exists( lambda y: y.startswith("M"), x)):
...
-jim
> Peter Otten wrote:
>
>> Jim Newton wrote:
>>
>>
>>> sorry, i do not understand. The python syntax is a bit
>>> difficult for me.
>>
>>
>>
>> Maybe I obscured the issue by comparing name attributes to a string
>> instead
>> of using a predicate() function.
>>
>>
>>> if i have a list x and a function f how do i know if
>>> there is an element of x on which f returns something
>>> other than False?
>>
>>
>>
>> Using the above identifiers, let's assume we are looking for a name
>> starting
>> with "M":
>>
>>
>>>>> x = ["Peter", "Paul", "Mary", "Jane"]
>>>>> def f(o):
>>
>>
>> ... print "checking", o
>> ... return o.startswith("M")
>> ...
>>
>> If we call
>>
>>
>>>>> map(f, x)
>>
>>
>> checking Peter
>> checking Paul
>> checking Mary
>> checking Jane
>> [False, False, True, False]
>>
>> it invokes f() for every item in x and returns the above list of
>> booleans.
>> The equivalent list comprehension would be [f(i) for i in x]. Now
>>
>>
>>>>> True in map(f, x)
>>
>>
>> checking Peter
>> checking Paul
>> checking Mary
>> checking Jane
>> True
>>
>> gives the correct result but unfortunately does too much work as we don't
>> need to calculate f("Jane") when we already know the outcome. Enter
>> generator
>>
>>
>>>>> def lazymap(predicate, seq):
>>
>>
>> ... for item in seq:
>> ... yield predicate(item)
>> ...
>>
>> which calulates f(item) as needed. Proof:
>>
>>
>>>>> True in lazymap(f, x)
>>
>>
>> checking Peter
>> checking Paul
>> checking Mary
>> True
>>
>>
>> itertools.imap() is just the fast C implementation of lazymap().
>> The equivalent generator expression (new in Python 2.4) will be (f(i)
>> for i in x).
>>
>> Peter
>>
>
More information about the Python-list
mailing list