简体   繁体   English

python - lambda 可以有多个回报吗

[英]python - can lambda have more than one return

I know lambda doesn't have a return expression.我知道 lambda 没有返回表达式。 Normally一般

def one_return(a):
    #logic is here
    c = a + 1
    return c

can be written:可以写成:

lambda a : a + 1

How about write this one in a lambda function:在 lambda 函数中写这个怎么样:

def two_returns(a, b):
    # logic is here
    c = a + 1
    d = b * 1
    return c, d

Yes, it's possible.是的,这是可能的。 Because an expression such as this at the end of a function:因为在函数末尾有这样的表达式:

return a, b

Is equivalent to this:相当于:

return (a, b)

And there, you're really returning a single value: a tuple which happens to have two elements.在那里,您实际上返回了一个值:一个恰好有两个元素的元组。 So it's ok to have a lambda return a tuple, because it's a single value:所以让 lambda 返回一个元组是可以的,因为它是一个单一的值:

lambda a, b: (a, b) # here the return is implicit

当然:

lambda a, b: (a + 1, b * 1)

关于什么:

lambda a,b: (a+1,b*1)

Print the table of 2 and 3 with a single range iteration.使用单个范围迭代打印 2 和 3 的表。

>>> list(map(lambda n: n*2, range(1,11)))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


>>> list(map(lambda n: (n*2, n*3) , range(1,11)))
[(2, 3), (4, 6), (6, 9), (8, 12), (10, 15), (12, 18), (14, 21), (16, 24), (18, 27), (20, 30)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM