使用哪个更优选:lambda函数或嵌套函数('def')? [英] Which is more preferable to use: lambda functions or nested functions ('def')?

查看:75
本文介绍了使用哪个更优选:lambda函数或嵌套函数('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函数

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

嵌套功能

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

>>> b(5)
6

使用一种方法相对于另一种方法是否有优势? (性能?可读性?局限性?一致性?等)

Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)

这有关系吗?如果没有,那是否违反了Pythonic原理:

Does it even matter? If it doesn't then does that violate the Pythonic principle:

应该有一种(最好只有一种)明显的方式.

推荐答案

如果需要将lambda分配给名称,请改用def. def只是分配的语法糖,因此结果相同,并且更加灵活和可读.

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.

lambda s只能用于一次,扔掉没有名称的函数.

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.

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

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.

对于确实需要一个小的函数对象的情况,应使用operator模块函数,例如operator.add而不是lambda x, y: x + y

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

如果仍然需要一些lambda未包括在内,则可以考虑编写def,只是为了提高可读性.如果功能比operator模块的功能复杂,则def可能更好.

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.

因此,现实世界中很好的lambda用例很少见.

So, real world good lambda use cases are very rare.

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

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