使用哪个更优选:lambda函数或嵌套函数('def')?

编程入门 行业动态 更新时间:2024-10-17 13:39:18
本文介绍了使用哪个更优选: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')?

本文发布于:2023-11-02 14:18:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552635.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   嵌套   lambda   def

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!