如何用多行编写python lambda?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14843777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:37:46  来源:igfitidea点击:

How to write python lambda with multiple lines?

pythonlambda

提问by omega

In python, how can you write a lambda function taking multiple lines. I tried

在 python 中,如何编写多行的 lambda 函数。我试过

d = lambda x: if x:
                 return 1
              else 
                 return 2

but I am getting errors...

但我收到错误...

采纳答案by Gareth Latty

Use definstead.

使用def来代替。

def d(x):
    if x:
        return 1
    else:
        return 2

All python functions are first order objects (they can be passed as arguments), lambdais just a convenient way to make short ones. In general, you are better off using a normal function definition if it becomes anything beyond one line of simple code.

所有 python 函数都是一阶对象(它们可以作为参数传递),lambda只是一种制作短函数的便捷方法。一般来说,如果普通函数定义超出一行简单代码,则最好使用普通函数定义。

Even then, in fact, if you are assigning it to a name, I would always use defover lambda. lambdais really only a good idea when defining short keyfunctions, for use with sorted(), for example, as they can be placed inline into the function call.

即便如此,事实上,如果您将其分配给一个名称,我总是会使用defover lambdalambda在定义短key函数时确实只是一个好主意sorted(),例如用于 ,因为它们可以内联到函数调用中。

Note that, in your case, a ternary operator would do the job (lambda x: 1 if x else 2), but I'm presuming this is a simplified case.

请注意,在您的情况下,三元运算符会完成这项工作 ( lambda x: 1 if x else 2),但我认为这是一个简化的情况。

(As a code golf note, this could also be done in less code as lambda x: bool(x)+1- of course, that's highly unreadable and a bad idea.)

(作为代码高尔夫笔记,这也可以用更少的代码来完成lambda x: bool(x)+1- 当然,这是非常不可读的,也是一个坏主意。)

回答by K. Brafford

Here's a correct version of what you are trying to do:

这是您尝试执行的操作的正确版本:

d = lambda x: 1 if x else 2

But I am not sure why you want to do that.

但我不确定你为什么要这样做。

回答by David Unric

lambdaconstruct in Python is limited to an expression only, no statements are allowed

lambdaPython 中的构造仅限于表达式,不允许使用任何语句

While keeping the above mentioned constraint, you can write an expression with multiple lines using backslash char, of course:

在保持上述约束的同时,您当然可以使用反斜杠字符编写多行表达式:

>>> fn = lambda x: 1 if x \
                     else 2
>>> fn(True)
>>> 1
>>> fn(False)
>>> 2