lambda 有什么用?

发布于 2024-07-21 07:44:51 字数 1436 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

じ违心 2024-07-28 07:44:52

一般来说,Lambda 与函数式编程风格有着密切的联系。 通过将函数应用于某些数据并合并结果来解决问题的想法是谷歌用来实现其大部分算法的。

以函数式编程风格编写的程序很容易并行化,因此对于现代多核机器变得越来越重要。
简而言之,不,你不应该忘记它们。

Lambdas are deeply linked to functional programming style in general. The idea that you can solve problems by applying a function to some data, and merging the results, is what google uses to implement most of its algorithms.

Programs written in functional programming style, are easily parallelized and hence are becoming more and more important with modern multi-core machines.
So in short, NO you should not forget them.

白首有我共你 2024-07-28 07:44:52

首先恭喜你成功解出了 lambda。 在我看来,这是一个非常强大的结构。 如今函数式编程语言的趋势无疑表明它既不应该被避免,也不应该在不久的将来被重新定义。

你只需要有一点不同的想法。 我相信很快你就会喜欢它。 但如果你只处理 python,请小心。 因为 lambda 不是真正的闭包,所以它以某种方式“损坏”: python 的 lambda 被破坏了

First congrats that managed to figure out lambda. In my opinion this is really powerful construct to act with. The trend these days towards functional programming languages is surely an indicator that it neither should be avoided nor it will be redefined in the near future.

You just have to think a little bit different. I'm sure soon you will love it. But be careful if you deal only with python. Because the lambda is not a real closure, it is "broken" somehow: pythons lambda is broken

慵挽 2024-07-28 07:44:52

我刚刚开始使用 Python,并首先接触了 Lambda - 这花了我一段时间才弄清楚。

请注意,这并不是对任何事情的谴责。 每个人都有不同的东西,这些东西并不容易得到。

lambda 是现实生活中应该被遗忘的那些“有趣”的语言项目之一吗?

不。

我确信在某些边缘情况下可能需要它,但考虑到它的模糊性,

它并不晦涩。 我过去工作过的两个团队,每个人都一直使用这个功能。

它在未来版本中被重新定义的潜力(我的假设基于它的各种定义)

除了几年前修复闭包语义之外,我还没有看到在 Python 中重新定义它的严肃建议。

以及编码清晰度的降低 - 应该避免吗?

如果你使用得当的话,这一点也同样清楚。 相反,拥有更多可用的语言结构可以提高清晰度。

这让我想起了 C 类型的溢出(缓冲区溢出) - 指向顶部变量并重载以设置其他字段值...有点技术表演技巧,但维护编码员的噩梦..

Lambda 就像缓冲区溢出? 哇。 如果您认为 lambda 是“维护噩梦”,我无法想象您如何使用它。

I'm just beginning Python and ran head first into Lambda- which took me a while to figure out.

Note that this isn't a condemnation of anything. Everybody has a different set of things that don't come easily.

Is lambda one of those 'interesting' language items that in real life should be forgotten?

No.

I'm sure there are some edge cases where it might be needed, but given the obscurity of it,

It's not obscure. The past 2 teams I've worked on, everybody used this feature all the time.

the potential of it being redefined in future releases (my assumption based on the various definitions of it)

I've seen no serious proposals to redefine it in Python, beyond fixing the closure semantics a few years ago.

and the reduced coding clarity - should it be avoided?

It's not less clear, if you're using it right. On the contrary, having more language constructs available increases clarity.

This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values...sort of a techie showmanship but maintenance coder nightmare..

Lambda is like buffer overflow? Wow. I can't imagine how you're using lambda if you think it's a "maintenance nightmare".

智商已欠费 2024-07-28 07:44:52

使用 lambda 的一个有用案例是提高长列表推导式的可读性
在此示例中,为了清楚起见,loop_dic 很短,但想象 loop_dic 很长。 如果您只使用包含 i 的普通值,而不是该值的 lambda 版本,您将收到 NameError

>>> lis = [{"name": "Peter"}, {"name": "Josef"}]

>>> loop_dic = lambda i: {"name": i["name"] + " Wallace" }
>>> new_lis = [loop_dic(i) for i in lis]

>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]

代替

>>> lis = [{"name": "Peter"}, {"name": "Josef"}]

>>> new_lis = [{"name": i["name"] + " Wallace"} for i in lis]

>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]

A useful case for using lambdas is to improve the readability of long list comprehensions.
In this example loop_dic is short for clarity but imagine loop_dic being very long. If you would just use a plain value that includes i instead of the lambda version of that value you would get a NameError.

>>> lis = [{"name": "Peter"}, {"name": "Josef"}]

>>> loop_dic = lambda i: {"name": i["name"] + " Wallace" }
>>> new_lis = [loop_dic(i) for i in lis]

>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]

Instead of

>>> lis = [{"name": "Peter"}, {"name": "Josef"}]

>>> new_lis = [{"name": i["name"] + " Wallace"} for i in lis]

>>> new_lis
[{'name': 'Peter Wallace'}, {'name': 'Josef Wallace'}]
余生一个溪 2024-07-28 07:44:52

我使用 lambda 来避免代码重复。 这将使该功能易于理解
例如:

def a_func()
  ...
  if some_conditon:
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)
  else
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)

我用临时 lambda 替换它

def a_func()
  ...
  call_big_f = lambda args_that_change: call_some_big_func(arg1, arg2, arg3, args_that_change)
  if some_conditon:
     ...
     call_big_f(argX)
  else
     ...
     call_big_f(argY)

I use lambdas to avoid code duplication. It would make the function easily comprehensible
Eg:

def a_func()
  ...
  if some_conditon:
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)
  else
     ...
     call_some_big_func(arg1, arg2, arg3, arg4...)

I replace that with a temp lambda

def a_func()
  ...
  call_big_f = lambda args_that_change: call_some_big_func(arg1, arg2, arg3, args_that_change)
  if some_conditon:
     ...
     call_big_f(argX)
  else
     ...
     call_big_f(argY)
尾戒 2024-07-28 07:44:52

我今天开始阅读 David Mertz 的书《Python 中的文本处理》。 虽然他对 Lambda 进行了相当简洁的描述,但第一章中的示例与附录 A 中的解释相结合,让我(终于)明白了它们的含义,突然间我明白了它们的价值。 这并不是说他的解释对你有用,而且我仍处于发现阶段,因此除了以下内容之外,我不会尝试添加这些回应:
我是 Python 新手
我是面向对象编程的新手
Lambda 对我来说是一场斗争
现在我读了 Mertz,我想我明白了它们,并且我认为它们非常有用,因为我认为它们提供了一种更清晰的编程方法。

他重现了 Python 的禅宗,其中一行是简单胜于复杂。作为一名非 OOP 程序员,使用 lambda 阅读代码(直到上周列表推导式),我想 -这很简单吗?。 今天我终于意识到,实际上这些功能使代码比替代方案(总是某种循环)更具可读性和可理解性。 我还意识到,就像财务报表一样,Python 不是为新手用户设计的,而是为想要接受教育的用户设计的。 我不敢相信这种语言有多么强大。 当我(最终)意识到 lambda 的目的和价值时,我想撕掉大约 30 个程序,并在适当的地方重新开始添加 lambda。

I started reading David Mertz's book today 'Text Processing in Python.' While he has a fairly terse description of Lambda's the examples in the first chapter combined with the explanation in Appendix A made them jump off the page for me (finally) and all of a sudden I understood their value. That is not to say his explanation will work for you and I am still at the discovery stage so I will not attempt to add to these responses other than the following:
I am new to Python
I am new to OOP
Lambdas were a struggle for me
Now that I read Mertz, I think I get them and I see them as very useful as I think they allow a cleaner approach to programming.

He reproduces the Zen of Python, one line of which is Simple is better than complex. As a non-OOP programmer reading code with lambdas (and until last week list comprehensions) I have thought-This is simple?. I finally realized today that actually these features make the code much more readable, and understandable than the alternative-which is invariably a loop of some sort. I also realized that like financial statements-Python was not designed for the novice user, rather it is designed for the user that wants to get educated. I can't believe how powerful this language is. When it dawned on me (finally) the purpose and value of lambdas I wanted to rip up about 30 programs and start over putting in lambdas where appropriate.

梦途 2024-07-28 07:44:52

我可以给你举一个我实际上需要 lambda 的例子。 我正在制作一个图形程序,其中用户右键单击文件并为其分配三个选项之一。 事实证明,在 Tkinter(我正在编写的 GUI 接口程序)中,当有人按下按钮时,它无法分配给接受参数的命令。 因此,如果我选择其中一个选项并希望我选择的结果是:

print 'hi there'

那就没什么大不了的。 但是如果我需要我的选择有一个特定的细节怎么办? 例如,如果我选择选项 A,它会调用一个函数,该函数接受一些依赖于选项 A、B 或 C 的参数,TKinter 无法支持这一点。 实际上,Lamda 是解决这个问题的唯一选择......

I can give you an example where I actually needed lambda serious. I'm making a graphical program, where the use right clicks on a file and assigns it one of three options. It turns out that in Tkinter (the GUI interfacing program I'm writing this in), when someone presses a button, it can't be assigned to a command that takes in arguments. So if I chose one of the options and wanted the result of my choice to be:

print 'hi there'

Then no big deal. But what if I need my choice to have a particular detail. For example, if I choose choice A, it calls a function that takes in some argument that is dependent on the choice A, B or C, TKinter could not support this. Lamda was the only option to get around this actually...

撕心裂肺的伤痛 2024-07-28 07:44:52

我经常使用它,主要作为 空对象 或将参数部分绑定到函数。

以下是示例:

实现空对象模式:

{
    DATA_PACKET: self.handle_data_packets
    NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

对于参数绑定:

假设我有以下 API

def dump_hex(file, var)
    # some code
    pass

class X(object):
    #...
    def packet_received(data):
        # some kind of preprocessing
        self.callback(data)
    #...

然后,当我不想将收到的数据快速转储到文件中时,我会这样做:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()

I use it quite often, mainly as a null object or to partially bind parameters to a function.

Here are examples:

to implement null object pattern:

{
    DATA_PACKET: self.handle_data_packets
    NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

for parameter binding:

let say that I have the following API

def dump_hex(file, var)
    # some code
    pass

class X(object):
    #...
    def packet_received(data):
        # some kind of preprocessing
        self.callback(data)
    #...

Then, when I wan't to quickly dump the recieved data to a file I do that:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()
故人爱我别走 2024-07-28 07:44:52

我使用 lambda 来创建包含参数的回调。 在一行中编写 lambda 比编写一个方法来执行相同的功能更简洁。

例如:

import imported.module

def func():
    return lambda: imported.module.method("foo", "bar")

相对于:

import imported.module

def func():
    def cb():
        return imported.module.method("foo", "bar")
    return cb

I use lambda to create callbacks that include parameters. It's cleaner writing a lambda in one line than to write a method to perform the same functionality.

For example:

import imported.module

def func():
    return lambda: imported.module.method("foo", "bar")

as opposed to:

import imported.module

def func():
    def cb():
        return imported.module.method("foo", "bar")
    return cb
甜尕妞 2024-07-28 07:44:52

我是一名 Python 初学者,因此为了清楚地了解 lambda,我将其与“for”循环进行了比较; 在效率方面。
这是代码(python 2.7)-

import time
start = time.time() # Measure the time taken for execution

def first():
    squares = map(lambda x: x**2, range(10))
    # ^ Lambda
    end = time.time()
    elapsed = end - start
    print elapsed + ' seconds'
    return elapsed # gives 0.0 seconds

def second():
    lst = []
    for i in range(10):
        lst.append(i**2)
    # ^ a 'for' loop
    end = time.time()
    elapsed = end - start
    print elapsed + ' seconds'
    return elapsed # gives 0.0019998550415 seconds.

print abs(second() - first()) # Gives 0.0019998550415 seconds!(duh)

I'm a python beginner, so to getter a clear idea of lambda I compared it with a 'for' loop; in terms of efficiency.
Here's the code (python 2.7) -

import time
start = time.time() # Measure the time taken for execution

def first():
    squares = map(lambda x: x**2, range(10))
    # ^ Lambda
    end = time.time()
    elapsed = end - start
    print elapsed + ' seconds'
    return elapsed # gives 0.0 seconds

def second():
    lst = []
    for i in range(10):
        lst.append(i**2)
    # ^ a 'for' loop
    end = time.time()
    elapsed = end - start
    print elapsed + ' seconds'
    return elapsed # gives 0.0019998550415 seconds.

print abs(second() - first()) # Gives 0.0019998550415 seconds!(duh)
狼性发作 2024-07-28 07:44:52

Lambda 是一个过程构造函数。 尽管Python的lambda不是很强大,但您可以在运行时综合程序。 请注意,很少有人理解这种编程。

Lambda is a procedure constructor. You can synthesize programs at run-time, although Python's lambda is not very powerful. Note that few people understand that kind of programming.

冷月断魂刀 2024-07-28 07:44:51

您在谈论 lambda 表达式 吗? 像

lambda x: x**2 + 2*x - 5

这些东西其实还是蛮有用的。 Python 支持一种称为函数式编程的编程风格,您可以将函数传递给其他函数来执行操作。 示例:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

mult3 设置为 [3, 6, 9],即原始列表中 3 的倍数的元素。这更短(而且,有人可能会说,更清晰) )当然

def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

,在这种特殊情况下,您可以做与列表理解相同的事情:(

mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]

甚至作为 range(3,10,3)),但是还有许多其他更复杂的方法在无法使用列表理解的用例中,lambda 函数可能是写出某些内容的最短方法。

  • 从另一个函数返回一个函数

    <前><代码>>>>> def 变换(n):
    ...返回 lambda x: x + n
    ...
    >>>>> f = 变换(3)
    >>>>> f(4)
    7

    这通常用于创建函数包装器,例如 Python 的装饰器。

  • 使用reduce()组合可迭代序列的元素

    <前><代码>>>>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])
    '1, 2, 3, 4, 5, 6, 7, 8, 9'

  • 按备用键排序

    <前><代码>>>>> 排序([1,2,3,4,5,6,7,8,9],key=lambda x:abs(5-x))
    [5,4,6,3,7,2,8,1,9]

我经常使用 lambda 函数。 我花了一段时间才习惯它们,但最终我意识到它们是该语言非常有价值的一部分。

Are you talking about lambda expressions? Like

lambda x: x**2 + 2*x - 5

Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than

def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

Of course, in this particular case, you could do the same thing as a list comprehension:

mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]

(or even as range(3,10,3)), but there are many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out.

  • Returning a function from another function

      >>> def transform(n):
      ...     return lambda x: x + n
      ...
      >>> f = transform(3)
      >>> f(4)
      7
    

    This is often used to create function wrappers, such as Python's decorators.

  • Combining elements of an iterable sequence with reduce()

      >>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])
      '1, 2, 3, 4, 5, 6, 7, 8, 9'
    
  • Sorting by an alternate key

      >>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
      [5, 4, 6, 3, 7, 2, 8, 1, 9]
    

I use lambda functions on a regular basis. It took me a while to get used to them, but eventually I came to understand that they're a very valuable part of the language.

装纯掩盖桑 2024-07-28 07:44:51

lambda 只是一种表达function 的奇特方式。 除了它的名字之外,它没有任何晦涩、令人生畏或神秘的地方。 当您阅读以下行时,请在脑海中将 lambda 替换为 function

>>> f = lambda x: x + 1
>>> f(3)
4

它只是定义了 x 的函数。 其他一些语言,例如 R,明确表示:

> f = function(x) { x + 1 }
> f(3)
4

你明白了吗? 这是编程中最自然的事情之一。

lambda is just a fancy way of saying function. Other than its name, there is nothing obscure, intimidating or cryptic about it. When you read the following line, replace lambda by function in your mind:

>>> f = lambda x: x + 1
>>> f(3)
4

It just defines a function of x. Some other languages, like R, say it explicitly:

> f = function(x) { x + 1 }
> f(3)
4

You see? It's one of the most natural things to do in programming.

§普罗旺斯的薰衣草 2024-07-28 07:44:51

两行摘要:

  1. 闭包:非常有用。 学习它们、使用它们、热爱它们。
  2. Python 的 lambda 关键字:不必要,偶尔有用。 如果您发现自己用它做了一些非常复杂的事情,请将其放在一边并定义一个真正的函数。

The two-line summary:

  1. Closures: Very useful. Learn them, use them, love them.
  2. Python's lambda keyword: unnecessary, occasionally useful. If you find yourself doing anything remotely complex with it, put it away and define a real function.
余厌 2024-07-28 07:44:51

lambda 是处理高阶函数的非常重要的抽象机制的一部分。 要正确理解其价值,请观看来自 Abelson 和 Sussman,并阅读这本书 SICP

这些是相关的现代软件业务中的问题,并且变得越来越流行。

A lambda is part of a very important abstraction mechanism which deals with higher order functions. To get proper understanding of its value, please watch high quality lessons from Abelson and Sussman, and read the book SICP

These are relevant issues in modern software business, and becoming ever more popular.

尬尬 2024-07-28 07:44:51

我怀疑 lambda 会消失。
请参阅Guido 的帖子了解最终放弃尝试删除它的信息。 另请参阅冲突概述

您可以查看这篇文章,了解更多有关 Python 函数特性背后的历史:
http://python-history.blogspot.com /2009/04/origins-of-pythons-function-features.html

奇怪的是,最初引入 lambda 和其他函数特性的映射、过滤和归约函数在很大程度上已被列表推导式和生成器表达式所取代。 事实上,reduce 函数已从 Python 3.0 的内置函数列表中删除。 (但是,没有必要对删除 lambda、map 或过滤器提出投诉:它们会留下来。:-)

我自己的两分钱:就清晰度而言,lambda 很少值得。 一般来说,有一个更清晰的解决方案,不包含 lambda。

I doubt lambda will go away.
See Guido's post about finally giving up trying to remove it. Also see an outline of the conflict.

You might check out this post for more of a history about the deal behind Python's functional features:
http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html

Curiously, the map, filter, and reduce functions that originally motivated the introduction of lambda and other functional features have to a large extent been superseded by list comprehensions and generator expressions. In fact, the reduce function was removed from list of builtin functions in Python 3.0. (However, it's not necessary to send in complaints about the removal of lambda, map or filter: they are staying. :-)

My own two cents: Rarely is lambda worth it as far as clarity goes. Generally there is a more clear solution that doesn't include lambda.

去了角落 2024-07-28 07:44:51

lambda 在 GUI 编程中非常有用。 例如,假设您正在创建一组按钮,并且希望使用单个参数化回调,而不是每个按钮使用唯一的回调。 Lambda 让您轻松完成此任务:(

for value in ["one","two","three"]:
    b = tk.Button(label=value, command=lambda arg=value: my_callback(arg))
    b.pack()

注意:虽然这个问题专门询问 lambda ,但您也可以使用 functools.partial 以获得相同类型的结果)

另一种方法是为每个按钮创建一个单独的回调,这可能会导致重复的代码。

lambdas are extremely useful in GUI programming. For example, lets say you're creating a group of buttons and you want to use a single paramaterized callback rather than a unique callback per button. Lambda lets you accomplish that with ease:

for value in ["one","two","three"]:
    b = tk.Button(label=value, command=lambda arg=value: my_callback(arg))
    b.pack()

(Note: although this question is specifically asking about lambda, you can also use functools.partial to get the same type of result)

The alternative is to create a separate callback for each button which can lead to duplicated code.

荒路情人 2024-07-28 07:44:51

在 Python 中,lambda 只是一种内联定义函数的方式,

a = lambda x: x + 1
print a(1)

并且

def a(x): return x + 1
print a(1)

......完全相同

对于 lambda 来说,没有什么是常规函数做不到的——在 Python 中,函数就像其他任何东西一样是一个对象,而 lambda 只是定义一个函数:

>>> a = lambda x: x + 1
>>> type(a)
<type 'function'>

老实说,我认为 lambda 关键字是多余的在 Python 中——我从来没有需要使用它们(或者看到在可以更好地使用常规函数、列表理解或许多内置函数之一的情况下使用它们)

对于一个完全随机的例子,来自文章< a href="http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/" rel="noreferrer">"Python 的 lambda 被破坏了!":

要了解 lambda 是如何被破坏的,请尝试生成函数列表 fs=[f0,...,f9],其中 fi(n)=i+n 。 第一次尝试:

<前><代码>>>> fs = [(lambda n: i + n) for i in range(10)]
>>>>> FS[3](4)
13

我认为,即使这确实有效,它也是可怕且“非Pythonic”的,相同的功能可以用无数其他方式编写,例如:

>>> n = 4
>>> [i + n for i in range(10)]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

是的,它不一样,但我从来没有

请注意,我们可以使用 lambda 并仍然达到预期的效果
结果是这样的:

<前><代码>>>> fs = [(lambda n,i=i: i + n) for i in range(10)]
>>>>> FS[3](4)
7

编辑:

在某些情况下 lambda 很有用,例如,在 PyQt 应用程序中连接信号时通常很方便,如下所示:

w = PyQt4.QtGui.QLineEdit()
w.textChanged.connect(lambda event: dothing())

Just do w.textChanged.connect(dothing)会使用额外的 event 参数调用 dothing 方法并导致错误。 使用 lambda 意味着我们可以整齐地删除参数,而无需定义包装函数。

In Python, lambda is just a way of defining functions inline,

a = lambda x: x + 1
print a(1)

and..

def a(x): return x + 1
print a(1)

..are the exact same.

There is nothing you can do with lambda which you cannot do with a regular function—in Python functions are an object just like anything else, and lambdas simply define a function:

>>> a = lambda x: x + 1
>>> type(a)
<type 'function'>

I honestly think the lambda keyword is redundant in Python—I have never had the need to use them (or seen one used where a regular function, a list-comprehension or one of the many builtin functions could have been better used instead)

For a completely random example, from the article "Python’s lambda is broken!":

To see how lambda is broken, try generating a list of functions fs=[f0,...,f9] where fi(n)=i+n. First attempt:

>>> fs = [(lambda n: i + n) for i in range(10)]
>>> fs[3](4)
13

I would argue, even if that did work, it's horribly and "unpythonic", the same functionality could be written in countless other ways, for example:

>>> n = 4
>>> [i + n for i in range(10)]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Yes, it's not the same, but I have never seen a cause where generating a group of lambda functions in a list has been required. It might make sense in other languages, but Python is not Haskell (or Lisp, or ...)

Please note that we can use lambda and still achieve the desired
results in this way :

>>> fs = [(lambda n,i=i: i + n) for i in range(10)]
>>> fs[3](4)
7

Edit:

There are a few cases where lambda is useful, for example it's often convenient when connecting up signals in PyQt applications, like this:

w = PyQt4.QtGui.QLineEdit()
w.textChanged.connect(lambda event: dothing())

Just doing w.textChanged.connect(dothing) would call the dothing method with an extra event argument and cause an error. Using the lambda means we can tidily drop the argument without having to define a wrapping function.

深陷 2024-07-28 07:44:51

我发现 lambda 对于执行相同操作但针对不同情况的函数列表很有用。

就像 Mozilla 复数规则

plural_rules = [
    lambda n: 'all',
    lambda n: 'singular' if n == 1 else 'plural',
    lambda n: 'singular' if 0 <= n <= 1 else 'plural',
    ...
]
# Call plural rule #1 with argument 4 to find out which sentence form to use.
plural_rule[1](4) # returns 'plural'

如果您必须为所有那些你最终会发疯的函数定义一个函数。
另外,使用诸如 plural_rule_1plural_rule_2 等函数名称也不太好。并且您需要在以下情况下对其进行 eval()你依赖于一个变量函数 id 。

I find lambda useful for a list of functions that do the same, but for different circumstances.

Like the Mozilla plural rules:

plural_rules = [
    lambda n: 'all',
    lambda n: 'singular' if n == 1 else 'plural',
    lambda n: 'singular' if 0 <= n <= 1 else 'plural',
    ...
]
# Call plural rule #1 with argument 4 to find out which sentence form to use.
plural_rule[1](4) # returns 'plural'

If you'd have to define a function for all of those you'd go mad by the end of it.
Also, it wouldn't be nice with function names like plural_rule_1, plural_rule_2, etc. And you'd need to eval() it when you're depending on a variable function id.

命比纸薄 2024-07-28 07:44:51

使用 lambda 可以做的几乎所有事情,使用命名函数或列表和生成器表达式都可以做得更好。

因此,在大多数情况下,基本上在任何情况下您都应该只使用其中之一(可能除了在交互式解释器中编写的临时代码)。

Pretty much anything you can do with lambda you can do better with either named functions or list and generator expressions.

Consequently, for the most part you should just one of those in basically any situation (except maybe for scratch code written in the interactive interpreter).

涫野音 2024-07-28 07:44:51

我已经使用 Python 几年了,但从未遇到过需要 lambda 的情况。 实际上,正如教程所述,它只是为了语法糖。

I've been using Python for a few years and I've never run in to a case where I've needed lambda. Really, as the tutorial states, it's just for syntactic sugar.

绅刃 2024-07-28 07:44:51

Lambda 函数是一种创建函数的非官僚方式。

就是这样。 例如,假设您有 main 函数并且需要对值进行平方。 让我们看看传统方式和 lambda 方式来执行此操作:

传统方式:

def main():
...
...
y = square(some_number)
...
return something

def square(x):
    return x**2

lambda 方式:

def main():
...
square = lambda x: x**2
y = square(some_number)
return something

看到区别了吗?

Lambda 函数非常适合列表,例如列表推导式或映射。 事实上,列表理解是一种使用 lambda 表达自己的“Pythonic”方式。 例如:

>>>a = [1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]

让我们看看语法中每个元素的含义:

[]:“给我一个列表”

x**2 :“使用这个新函数”

for x in a:“进入a中的每个元素”

这很方便吧? 创建这样的函数。 让我们使用 lambda 重写它:

>>> square = lambda x: x**2
>>> [square(s) for x in a]
[1,4,9,16]

现在让我们使用 map,它是相同的东西,但更与语言无关。 Maps 接受 2 个参数:

(i) 一个函数

(ii) 一个可迭代对象

并为您提供一个列表,其中每个元素都是应用于可迭代对象每个元素的函数。

因此,使用映射我们可以:

>>> a = [1,2,3,4]
>>> squared_list = map(lambda x: x**2, a)

如果你掌握了 lambda 和映射,你将拥有以简洁的方式操作数据的强大能力。 Lambda 函数既不晦涩难懂,也不影响代码的清晰度。 不要将困难的事物与新的事物混淆。 一旦你开始使用它们,你就会发现它非常清晰。

Lambda function it's a non-bureaucratic way to create a function.

That's it. For example, let's supose you have your main function and need to square values. Let's see the traditional way and the lambda way to do this:

Traditional way:

def main():
...
...
y = square(some_number)
...
return something

def square(x):
    return x**2

The lambda way:

def main():
...
square = lambda x: x**2
y = square(some_number)
return something

See the difference?

Lambda functions go very well with lists, like lists comprehensions or map. In fact, list comprehension it's a "pythonic" way to express yourself using lambda. Ex:

>>>a = [1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]

Let's see what each elements of the syntax means:

[] : "Give me a list"

x**2 : "using this new-born function"

for x in a: "into each element in a"

That's convenient uh? Creating functions like this. Let's rewrite it using lambda:

>>> square = lambda x: x**2
>>> [square(s) for x in a]
[1,4,9,16]

Now let's use map, which is the same thing, but more language-neutral. Maps takes 2 arguments:

(i) one function

(ii) an iterable

And gives you a list where each element it's the function applied to each element of the iterable.

So, using map we would have:

>>> a = [1,2,3,4]
>>> squared_list = map(lambda x: x**2, a)

If you master lambdas and mapping, you will have a great power to manipulate data and in a concise way. Lambda functions are neither obscure nor take away code clarity. Don't confuse something hard with something new. Once you start using them, you will find it very clear.

梦醒时光 2024-07-28 07:44:51

我无法谈论 python 的 lambda 特定实现,但总的来说 lambda 函数确实很方便。 它们是函数式编程的核心技术(甚至可能是技术),并且它们在面向对象的程序中也非常有用。 对于某些类型的问题,它们是最好的解决方案,所以当然不应该被忘记!

我建议您阅读 闭包映射函数(链接到 python 文档,但它存在于几乎所有支持函数式构造的语言中)来了解它为什么有用。

I can't speak to python's particular implementation of lambda, but in general lambda functions are really handy. They're a core technique (maybe even THE technique) of functional programming, and they're also very useuful in object-oriented programs. For certain types of problems, they're the best solution, so certainly shouldn't be forgotten!

I suggest you read up on closures and the map function (that links to python docs, but it exists in nearly every language that supports functional constructs) to see why it's useful.

所有深爱都是秘密 2024-07-28 07:44:51

我认为 lambda 的优点之一是它被低估了,它可以推迟对简单形式的求值,直到需要该值为止。 让我解释。

许多库例程的实现都允许调用某些参数(lambda 就是其中之一)。 这个想法是,仅在使用它时(而不是调用它时)才计算实际值。 一个(人为的)例子可能有助于说明这一点。 假设您有一个例程将记录给定的时间戳。 您希望例程使用当前时间减去 30 分钟。 您可以像这样调用它

log_timestamp(datetime.datetime.now() - datetime.timedelta(minutes = 30))

现在假设仅当某个事件发生时才会调用实际函数,并且您希望仅在那时计算时间戳。 您可以这样做,

log_timestamp(lambda : datetime.datetime.now() - datetime.timedelta(minutes = 30))

假设 log_timestamp 可以处理这样的可调用对象,它将在需要时对其进行评估,并且您将获得当时的时间戳。

当然还有其他方法可以做到这一点(例如使用 operator 模块),但我希望我已经传达了这一点。

更新这里是一个稍微具体的现实世界的例子。

更新 2:我认为这是所谓的 thunk

One of the nice things about lambda that's in my opinion understated is that it's way of deferring an evaluation for simple forms till the value is needed. Let me explain.

Many library routines are implemented so that they allow certain parameters to be callables (of whom lambda is one). The idea is that the actual value will be computed only at the time when it's going to be used (rather that when it's called). An (contrived) example might help to illustrate the point. Suppose you have a routine which which was going to do log a given timestamp. You want the routine to use the current time minus 30 minutes. You'd call it like so

log_timestamp(datetime.datetime.now() - datetime.timedelta(minutes = 30))

Now suppose the actual function is going to be called only when a certain event occurs and you want the timestamp to be computed only at that time. You can do this like so

log_timestamp(lambda : datetime.datetime.now() - datetime.timedelta(minutes = 30))

Assuming the log_timestamp can handle callables like this, it will evaluate this when it needs it and you'll get the timestamp at that time.

There are of course alternate ways to do this (using the operator module for example) but I hope I've conveyed the point.

Update: Here is a slightly more concrete real world example.

Update 2: I think this is an example of what is called a thunk.

抱猫软卧 2024-07-28 07:44:51

如上所述,Python 中的 lambda 运算符定义了一个匿名函数,而 Python 中的函数则是闭包。 重要的是不要将闭包的概念与运算符 lambda 混淆,这对于它们来说只是语法上的美沙酮。

几年前,当我开始使用 Python 时,我经常使用 lambda 表达式,认为它们以及列表推导式都很酷。 然而,我编写并维护了一个用 Python 编写的大型网站,有数千个功能点。 我从经验中了解到,lambda 可能可以用来原型化事物,但除了节省一些按键之外,不提供任何内联函数(称为闭包)的功能,有时甚至不提供。

基本上这可以归结为几点:

  • 使用有意义的名称明确编写的软件更容易阅读。 根据定义,匿名闭包不能有有意义的名称,因为它们没有名称。 由于某种原因,这种简洁性似乎也影响了 lambda 参数,因此我们经常看到像 lambda x: x+1 这样的示例,
  • 重用命名闭包会更容易,因为当存在用来指代它们的名称。
  • 使用命名闭包而不是 lambda 来调试代码会更容易,因为名称将出现在回溯中以及错误周围。

这足以将它们四舍五入并将它们转换为命名闭包。 然而,我对匿名关闭还有另外两个不满。

第一个怨恨很简单,它们只是另一个不必要的关键字,使语言变得混乱。

第二个怨恨更深,在范式层面上,即我不喜欢他们提倡函数式编程风格,因为这种风格不如消息传递、面向对象或过程式风格灵活,因为 lambda 演算不是图灵-完整(幸运的是,在 Python 中,即使在 lambda 内部,我们仍然可以突破该限制)。 我认为 lambda 提倡这种风格的原因是:

  • 有一个隐式返回,即它们看起来“应该”是函数。

  • 它们是另一种更显式、更易读、更可重用且更通用的机制(方法)的替代状态隐藏机制。

我努力编写无 lambda 的 Python,并在看到时删除 lambda。 我认为如果没有 lambdas,Python 会是一种稍微好一点的语言,但这只是我的观点。

As stated above, the lambda operator in Python defines an anonymous function, and in Python functions are closures. It is important not to confuse the concept of closures with the operator lambda, which is merely syntactic methadone for them.

When I started in Python a few years ago, I used lambdas a lot, thinking they were cool, along with list comprehensions. However, I wrote and have to maintain a big website written in Python, with on the order of several thousand function points. I've learnt from experience that lambdas might be OK to prototype things with, but offer nothing over inline functions (named closures) except for saving a few key-stokes, or sometimes not.

Basically this boils down to several points:

  • it is easier to read software that is explicitly written using meaningful names. Anonymous closures by definition cannot have a meaningful name, as they have no name. This brevity seems, for some reason, to also infect lambda parameters, hence we often see examples like lambda x: x+1
  • it is easier to reuse named closures, as they can be referred to by name more than once, when there is a name to refer to them by.
  • it is easier to debug code that is using named closures instead of lambdas, because the name will appear in tracebacks, and around the error.

That's enough reason to round them up and convert them to named closures. However, I hold two other grudges against anonymous closures.

The first grudge is simply that they are just another unnecessary keyword cluttering up the language.

The second grudge is deeper and on the paradigm level, i.e. I do not like that they promote a functional-programming style, because that style is less flexible than the message passing, object oriented or procedural styles, because the lambda calculus is not Turing-complete (luckily in Python, we can still break out of that restriction even inside a lambda). The reasons I feel lambdas promote this style are:

  • There is an implicit return, i.e. they seem like they 'should' be functions.

  • They are an alternative state-hiding mechanism to another, more explicit, more readable, more reusable and more general mechanism: methods.

I try hard to write lambda-free Python, and remove lambdas on sight. I think Python would be a slightly better language without lambdas, but that's just my opinion.

你在我安 2024-07-28 07:44:51

Lambda 实际上是非常强大的构造,源于函数式编程的思想,并且在不久的将来 Python 中绝不会轻易对其进行修改、重新定义或删除。 它们可以帮助您编写更强大的代码,因为它允许您将函数作为参数传递,从而实现函数作为一等公民的想法。

Lambda 确实容易让人困惑,但是一旦获得了扎实的理解,您就可以编写干净优雅的代码,如下所示:

squared = map(lambda x: x*x, [1, 2, 3, 4, 5])

上面的代码行返回列表中数字的平方列表。 当然,您也可以这样做:

def square(x):
    return x*x

squared = map(square, [1, 2, 3, 4, 5])

很明显,前一种代码更短,如果您打算仅在一个地方使用 map 函数(或任何将函数作为参数的类似函数),则尤其如此。 这也使得代码更加直观和优雅。

另外,正如 @David Zaslavsky 在他的回答中提到的,列表理解并不总是可行的方法,特别是如果你的列表必须从一些晦涩的数学方式获取值。

从更实际的角度来看,最近 lambda 对我来说最大的优势之一是 GUI 和事件驱动编程。 如果您查看 Tkinter 中的回调,您会发现它们作为参数的只是触发它们的事件。 例如,

def define_bindings(widget):
    widget.bind("<Button-1>", do-something-cool)

def do-something-cool(event):
    #Your code to execute on the event trigger

现在如果您有一些论点需要传递怎么办? 就像传递 2 个参数来存储鼠标单击的坐标一样简单。 您可以轻松地这样做:

def main():
    # define widgets and other imp stuff
    x, y = None, None
    widget.bind("<Button-1>", lambda event: do-something-cool(x, y))

def do-something-cool(event, x, y):
    x = event.x
    y = event.y
    #Do other cool stuff

现在您可以说这可以使用全局变量来完成,但是您真的想为内存管理和泄漏而烦恼吗,特别是如果全局变量仅在一个特定的地方使用的话? 那将是糟糕的编程风格。

简而言之,lambda 非常棒,永远不应该被低估。 虽然 Python lambda 与 LISP lambda 不同(后者更强大),但您确实可以用它们做很多神奇的事情。

Lambdas are actually very powerful constructs that stem from ideas in functional programming, and it is something that by no means will be easily revised, redefined or removed in the near future of Python. They help you write code that is more powerful as it allows you to pass functions as parameters, thus the idea of functions as first-class citizens.

Lambdas do tend to get confusing, but once a solid understanding is obtained, you can write clean elegant code like this:

squared = map(lambda x: x*x, [1, 2, 3, 4, 5])

The above line of code returns a list of the squares of the numbers in the list. Ofcourse, you could also do it like:

def square(x):
    return x*x

squared = map(square, [1, 2, 3, 4, 5])

It is obvious the former code is shorter, and this is especially true if you intend to use the map function (or any similar function that takes a function as a parameter) in only one place. This also makes the code more intuitive and elegant.

Also, as @David Zaslavsky mentioned in his answer, list comprehensions are not always the way to go especially if your list has to get values from some obscure mathematical way.

From a more practical standpoint, one of the biggest advantages of lambdas for me recently has been in GUI and event-driven programming. If you take a look at callbacks in Tkinter, all they take as arguments are the event that triggered them. E.g.

def define_bindings(widget):
    widget.bind("<Button-1>", do-something-cool)

def do-something-cool(event):
    #Your code to execute on the event trigger

Now what if you had some arguments to pass? Something as simple as passing 2 arguments to store the coordinates of a mouse-click. You can easily do it like this:

def main():
    # define widgets and other imp stuff
    x, y = None, None
    widget.bind("<Button-1>", lambda event: do-something-cool(x, y))

def do-something-cool(event, x, y):
    x = event.x
    y = event.y
    #Do other cool stuff

Now you can argue that this can be done using global variables, but do you really want to bang your head worrying about memory management and leakage especially if the global variable will just be used in one particular place? That would be just poor programming style.

In short, lambdas are awesome and should never be underestimated. Python lambdas are not the same as LISP lambdas though (which are more powerful), but you can really do a lot of magical stuff with them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文