beginner question

Qiang.JL dragon at china.org
Tue Mar 26 02:29:33 EST 2002


"Bengt Richter" <bokr at oz.net> wrote in message
news:a7p5o2$5oe$0 at 216.39.172.122...
> On Tue, 26 Mar 2002 05:25:28 GMT, "Qiang.JL" <dragon at china.org> wrote:
>
> >for this line:
> >
> >>>> g=(lambda x: ' '.join(x.split())) or (lambda y: 'second')
> >
> I doubt if this expression is doing what you want. It is the same form as
>
>      g = a or b
>
> which will set g to a, unless a counts as false (e.g., None,'',[],(), or
zero),
> in which case g will be set to b irrespective of b's value. So your
expression
> is effectively equivalent to
>
>     g=(lambda x: ' '.join(x.split()))
>

sorry english is not my native language, but why equivalent ? are you saying
the second condition is useless?


> If you really don't want to use def and you want to use your original
> expressions, use another lambda to tie them together, e.g., (OTTOMH,
> not very well tested ;-)
>
>  >>> g = lambda x: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y:
'second')(str(x))
>  >>> g('   ')
>  'second'
>  >>> g(g)
>  '<function <lambda> at 0x007DB060>'
>  >>> g(' a     bc    def')
>  'a bc def'
>
> Notice that the ouside lambda has a body that both defines _and_ calls the
internal lambdas
> with the str()-protected arguments. The second lambda will only be called
if the first one
> returns ''. The outside lambda then returns the result from whichever
internal one.
>
> But I'd say that's pretty ugly to read compared to
>
>  >>> def g(x):
>  ...     return ' '.join(str(x).split()) or 'second'
>  ...
>
> ;-)
>
> Regards,
> Bengt Richter
>

if the original lambdas work like yours why you add another one outside ? it
seems does the same thing.
Weird i run into problem with this one ..

>>> def g(x):
 return ' '.join(str(x).split()) or 'second'

>>> g(0)
'0'
>>> g('')
'second'
>>> g=(lambda x: ' '.join(str(x).split())) or (lambda x: 'second')
>>> g('')
''            # why it prints '' instead of 'second' ??????
>>> g(0)
'0'

what's wrong here ?

thanks

Q.





More information about the Python-list mailing list