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

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

问题描述

我是Python新手。我的任务很简单-我需要一个可以批量使用的功能列表。所以我用一些例子戏弄了它,例如

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)]

令人惊讶的是,

[f(0) for f in fs]

给我结果例如 [9,9,9,9,9,9,9,9,9,9] 。这不是我期望的,因为我希望变量 i 在不同的函数中具有不同的值。

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.

所以我的问题是:


  1. 是lambda全局变量 i 还是

python是否具有与javascript中的 closure相同的概念?我的意思是这里的每个lambda都保存了对 i 变量的引用,还是只保存了 i 值的副本

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?

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

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]

通常,Python支持类似于Java的闭包概念。但是,对于列表理解内的lambda表达式的 specific 情况,似乎 i 仅绑定一次并采用了继承,使每个返回的函数都像 i 一样工作。上面的hack明确地将每个 i 的值传递给一个lambda,它使用捕获的值 y 返回另一个lambda。

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天全站免登陆