conditionals in lambdas?
Donald O'Donnell
donod at home.com
Fri Nov 3 22:12:03 EST 2000
Sure you can:
>>> L = lambda string: string[:3] == 'yes'
>>> L('yesterday')
1
>>> L('tomorrow')
0
In fact you can do some pretty powerful stuff without using any
statements at all, only logical expressions.
For example:
>>> lambda sep: sep=='/' and 2 or sep==',' and 3 or sep=='-' and 4 or 5
this will return 2, 3, 4 for arguments '/', ',', '-' and 5 for anything
else.
To quote from the Python Reference Manual (Section 5.10 Boolean
operations):
"Note that neither `and` nor `or` restrict the value and type they
return
to 0 or 1, but rather return the last evaluated argument. ..."
There's more in the manual. Check it out, and have fun.
There's-more-to-logical-expressions-than-true-and-false-ly yours,
Don O'Donnell
"Michael P. Soulier" wrote:
>
> Hey people. If I want to put conditions in a lambda function, how would I
> go about that?
>
> def test(string):
> if string[:3] == 'yes:
> return 1
> else:
> return 0
>
> I'd like to make something like this a lambda function. Is that possible?
>
> Mike
>
> --
More information about the Python-list
mailing list