如何用多行写python lambda? [英] How to write python lambda with multiple lines?
问题描述
在python中,如何编写包含多行代码的lambda函数.我尝试过
In python, how can you write a lambda function taking multiple lines. I tried
d = lambda x: if x:
return 1
else
return 2
但是我遇到了错误...
but I am getting errors...
推荐答案
请改用def
.
def d(x):
if x:
return 1
else:
return 2
所有python函数都是一阶对象(它们可以作为参数传递),lambda
只是一种简短的简便方法.通常,如果普通函数定义超出了简单代码的一行,则最好使用普通函数定义.
All python functions are first order objects (they can be passed as arguments), lambda
is 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.
实际上,即使您将其分配给一个名称,我也总是会在lambda
上使用def
.在定义短的key
函数(例如与sorted()
一起使用)时,lambda
实际上只是一个好主意,因为它们可以内联放置在函数调用中.
Even then, in fact, if you are assigning it to a name, I would always use def
over lambda
. lambda
is really only a good idea when defining short key
functions, for use with sorted()
, for example, as they can be placed inline into the function call.
请注意,在您的情况下,三元运算符可以完成此任务(lambda x: 1 if x else 2
),但是我认为这是一种简化的情况.
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: bool(x)+1
更少的代码来完成-当然,这是非常难以理解的,也是一个坏主意.)
(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.)
这篇关于如何用多行写python lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!