哪个更可取:lambda 函数或嵌套函数 ('def')? [英] Which is more preferable to use: lambda functions or nested functions ('def')?
问题描述
我主要使用 lambda 函数,但有时使用似乎提供相同行为的嵌套函数.
这里有一些简单的例子,如果在另一个函数中找到它们,它们在功能上做同样的事情:
Lambda 函数
<预><代码>>>>a = λ x : 1 + x>>>一(5)6嵌套函数
<预><代码>>>>def b(x): 返回 1 + x>>>乙(5)6使用一种比另一种有优势吗?(性能?可读性?限制?一致性?等)
这还重要吗?如果没有,那么这是否违反了 Pythonic 原则:
<块引用>如果您需要将 lambda
分配给名称,请改用 def
.def
只是赋值的语法糖,所以结果是一样的,而且它们更加灵活和可读.
lambda
s 可以用于使用一次,扔掉没有名字的函数.
然而,这种用例非常罕见.您很少需要传递未命名的函数对象.
内置map()
和filter()
需要函数对象,但列表推导式 和生成器表达式通常比那些函数更具可读性,并且可以涵盖所有用例,而无需 lambda.
如果你真的需要一个小函数对象,你应该使用operator
模块函数,比如operator.add
而不是lambda x,y:x + y
如果您仍然需要一些未涵盖的 lambda
,您可以考虑编写一个 def
,以提高可读性.如果函数比 operator
模块中的函数更复杂,def
可能更好.
因此,现实世界中好的 lambda
用例非常罕见.
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
Lambda function
>>> a = lambda x : 1 + x
>>> a(5)
6
Nested function
>>> def b(x): return 1 + x
>>> b(5)
6
Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)
Does it even matter? If it doesn't then does that violate the Pythonic principle:
There should be one-- and preferably only one --obvious way to do it..
If you need to assign the lambda
to a name, use a def
instead. def
s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
lambda
s can be used for use once, throw away functions which won't have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
The builtins map()
and filter()
need function objects, but list comprehensions and generator expressions are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the operator
module functions, like operator.add
instead of lambda x, y: x + y
If you still need some lambda
not covered, you might consider writing a def
, just to be more readable. If the function is more complex than the ones at operator
module, a def
is probably better.
So, real world good lambda
use cases are very rare.
这篇关于哪个更可取:lambda 函数或嵌套函数 ('def')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!