哪个更适合在Python中使用:lambda函数或嵌套函数('def')? [英] Which is more preferable to use in Python: lambda functions or nested functions ('def')?

查看:175
本文介绍了哪个更适合在Python中使用:lambda函数或嵌套函数('def')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用lambda函数,但有时使用似乎提供相同行为的嵌套函数。



以下是一些简单的例子,它们在功能上做同样的事情,如果在另一个函数中找到:

Lambda函数

 >>> a = lambda x:1 + x 
>>> a(5)
6

嵌套函数

 >>> def b(x):return 1 + x 

>>> b(5)
6

使用一种优势是否有优势? (性能?可读性?限制?一致性?等)

它甚至重要吗?如果没有,那么这是否违反了Pythonic原则:


应该有一个 - 最好只有一个 - 显而易见的方法


解决方案

如果您需要将 lambda 分配给名称,请使用 def 代替。 def s仅仅是赋值语句的糖,所以结果是一样的,而且它们更加灵活和可读。



lambda s可以用于使用一次,扔掉不会有名称的函数。



然而,这种用例非常罕见。您很少需要传递未命名的函数对象。



内置 map() filter()需要函数对象,但列表解析生成器表达式通常比这些函数更具可读性,并且可以涵盖所有用例,需要lambda。

对于你确实需要一个小函数对象的情况,你应该使用运算符模块函数,比如 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. defs are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.

lambdas 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.

这篇关于哪个更适合在Python中使用:lambda函数或嵌套函数('def')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆