lambda 函数如何在 python 中引用它的参数? [英] How does a lambda function refer to its parameters in python?

查看:25
本文介绍了lambda 函数如何在 python 中引用它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我的任务非常简单——我需要一个可用于批量处理的函数列表.所以我玩弄了一些例子,比如

fs = [lambda x: x + i for i in xrange(10)]

出人意料的是,

[f(0) for f in fs]

给了我类似 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] 的结果.这不是我所期望的,因为我希望变量 i 在不同的函数中具有不同的值.

所以我的问题是:

  1. lambda 中的变量 i 是全局的还是局部的?

  2. python 和 javascript 中的 'closure' 有相同的概念吗?我的意思是这里的每个 lambda 都持有对 i 变量的引用,还是他们只持有每个 i 值的副本?

  3. 如果我希望在这种情况下输出为 [0, 1, .....9] 该怎么办?

解决方案

看起来有点乱,但你可以通过这样做来得到你想要的:

<预><代码>>>>fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]>>>[f(0) for f in fs][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

通常 Python 支持类似于您在 Javascript 中使用的闭包"概念.然而,对于列表推导式中 lambda 表达式的这种特殊情况,似乎 i 只绑定一次并连续接受每个值,留下每个返回的函数就像 i 是 9 一样. 上面的 hack 明确地将 i 的每个值传递给一个 lambda,该 lambda 使用捕获的 y.

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like

fs = [lambda x: x + i for i in xrange(10)]

Surprisingly, the call of

[f(0) for f in fs]

gave me the result like [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]. It was not what I expected as I'd like the variable i has different values in different functions.

So My question is:

  1. Is the variable i in lambda global or local?

  2. Does python has the same concept like 'closure' in javascript? I mean does each lambda here holds a reference to the i variable or they just hold a copy of the value of i in each?

  3. What should I do if I'd like the output to be [0, 1, .....9] in this case?

解决方案

It looks a bit messy, but you can get what you want by doing something like this:

>>> fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]
>>> [f(0) for f in fs]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Normally Python supports the "closure" concept similar to what you're used to in Javascript. However, for this particular case of a lambda expression inside a list comprehension, it seems as though i is only bound once and takes on each value in succession, leaving each returned function to act as though i is 9. The above hack explicitly passes each value of i into a lambda that returns another lambda, using the captured value of y.

这篇关于lambda 函数如何在 python 中引用它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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