conditionals in lambdas?
Joshua Muskovitz
josh at open.com
Fri Nov 3 16:16:50 EST 2000
Although the general case of adding conditionals in a lambda isn't allowed,
if you can restructure the requirement to an expression, then you can make
it work. For your example:
> def test(string):
> if string[:3] == 'yes:
> return 1
> else:
> return 0
You can do the following:
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> a = lambda x: x[:3] == 'yes'
>>> a('')
0
>>> a('yes')
1
>>> a('yess')
1
>>>
This works because an equality comparison expression already returns 0 or 1.
You can get creative (or silly, depending on how you look at it) by taking
that result and using it inside something larger:
>>> a = lambda x: ['does not start with "yes"', 'starts with "yes"'][x[:3]
== 'yes']
>>> a('')
'does not start with "yes"'
>>> a('yes')
'starts with "yes"'
>>> a('yess')
'starts with "yes"'
>>>
And of course, you get can get much sillier than this, but you get the idea.
-- josh
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 80,000 Newsgroups - 16 Different Servers! =-----
More information about the Python-list
mailing list