conditionals in lambdas?

Greg Ball gball at cfa.harvard.edu
Fri Nov 3 18:29:35 EST 2000


Michael P. Soulier wrote

> filecontents = filter(filterloaddata, filecontents)
> 
> def filterloaddata(string):
>     if string[:9] == '#LOADDATA':
>         return 1
>     else:
>         return 0

This is very easily done using a lambda.

filecontents = filter(lambda s: s[:9]=='#LOADDATA', filecontents)

You just have to know that the relational operators are expressions and
can appear anywhere (they are 1 or 0 for true or false...). This is how I
use filter() most of the time.

You can do much more complicated things to make up for lack of control
flow in expressions, using logical operators and indexing, but it's a case
of diminishing returns.

-Greg Ball











More information about the Python-list mailing list