Can you assign variables in a lambda?

后端 未结 7 509
礼貌的吻别
礼貌的吻别 2020-12-19 03:43

I was using a lambda statement to perform math, and happened to repeatedly use one certain value. Therefore I was wondering if it was possible to assign and use

相关标签:
7条回答
  • 2020-12-19 04:36

    Nope, you can't. Only expressions allowed in lambda:

    lambda_expr        ::=  "lambda" [parameter_list]: expression
    lambda_expr_nocond ::=  "lambda" [parameter_list]: expression_nocond
    

    You could, however, define a second lambda inside the lambda and immediately call it with the parameter you want. (Whether that's really better might be another question.)

    >>> a = lambda n: ((3+2*n), n*(3+2*n))  # for reference, with repetition
    >>> a(42)
    (87, 3654)
    >>> a2 = lambda n: (lambda b: (b, n*b))(3+2*n)  # lambda inside lambda
    >>> a2(42)
    (87, 3654)
    >>> a3 = lambda n: (lambda b=3+2*n: (b, n*b))()  # using default parameter
    >>> a3(42)
    (87, 3654)
    

    Of course, both the outer and the inner lambda can have more than one parameter, i.e. you can define multiple "variables" at once. The benefit of this approach over, e.g., defining a second lambda outside of the first is, that you can still also use the original parameters (not possible if you invoked a with b pre-calculated) and you have to do the calculation for b only once (other than repeatedly invoking a function for the calculation of b within a).


    Also, inspired by the top answer to the linked question, you could also define one or more variables as part of a list comprehension or generator within the lambda, and then get the next (first and only) result from that generator or list:

    >>> a4 = lambda n: next((b, n*b) for b in [3+2*n])
    >>> a4(42)
    (87, 3654)
    

    However, I think the intent behind the lambda-in-a-lambda is a bit clearer. Finally, keep in mind that instead of a one-line lambda, you could also just use a much clearer three-line def statement...


    Also, starting with Python 3.8, there will be assignment expressions, which should make it possible to write something like this. (Note that I could not try/verify this as I do not have Python 3.8 yet.)

    >>> a5 = lambda n: ((b := 3+2*n), n*b))
    
    0 讨论(0)
提交回复
热议问题