beginner question

Bengt Richter bokr at oz.net
Tue Mar 26 01:50:42 EST 2002


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()))

Since you are binding to g anyway, you might as well do it the straight forward way:

    def g(x):
        return ' '.join(x.split())

>now by calling g(str(something)) make sure i always pass a string to the
>function(ignore exception if improper stuff in str). I want to know what

If you are always going to call it that way, it would make more sense to
put it in the function, e.g.,

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

>parameter i can pass to the lambda function so that the first condition
>false then second condition get executed?

If you just want an alternate expression when the first is "false", just
add it to the return expression, e.g.,

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

>or as long as i pass a string,it's always true for the first condition?
>
The best way to find out is play with the interpreter. It will tell you:

 >>> def g(x):
 ...     return ' '.join(str(x).split())
 ...
 >>> g('')
 ''
Or try it with a lot of mixed white space, which split will
get rid of: 

 >>> g("""    \t   \r\r\r\n\n\n
 ... \t               \t
 ...           \f
 ... """)
 ''

Now what will happen if we tack on an 'or' to that expression? Trying it:

 >>> '' or 'second'
 'second'

What happens if we pass a non-string as argument? Try it!
(e.g., g is a function, not a string):

 >>> def g(x):
 ...     return ' '.join(str(x).split()) or 'second'
 ...
 >>> g(g)
 '<function g at 0x007DB100>'
 >>> g(0)
 '0'
 >>> g('   ')
 'second'
 >>> g('')
 'second'

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




More information about the Python-list mailing list