如何创建 lambda 列表(在列表理解/for 循环中)? [英] How do I create a list of lambdas (in a list comprehension/for loop)?

查看:42
本文介绍了如何创建 lambda 列表(在列表理解/for 循环中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Python 中的常量列表创建一个 lambda 对象列表;例如:

I want to create a list of lambda objects from a list of constants in Python; for instance:

listOfNumbers = [1,2,3,4,5]
square = lambda x: x * x
listOfLambdas = [lambda: square(i) for i in listOfNumbers]

这将创建一个 lambda 对象列表,但是,当我运行它们时:

This will create a list of lambda objects, however, when I run them:

for f in listOfLambdas:
    print f(),

我希望它会打印

1 4 9 16 25

相反,它打印:

25 25 25 25 25

似乎所有 lambda 表达式都被赋予了错误的参数.我做错了什么,有没有办法解决?我想我使用的是 Python 2.4.

It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think.

多一点尝试的东西,这样想出了这个:

a bit more of trying things and such came up with this:

listOfLambdas = []
for num in listOfNumbers:
    action = lambda: square(num)
    listOfLambdas.append(action)
    print action()

打印从 1 到 25 的预期方块,然后使用较早的打印语句:

Prints the expected squares from 1 to 25, but then using the earlier print statement:

for f in listOfLambdas:
    print f(),

仍然给我所有的25.现有的 lambda 对象在这两次打印调用之间有何变化?

still gives me all 25s. How did the existing lambda objects change between those two print calls?

相关问题:为什么结果是map()和list理解力不一样?

推荐答案

我猜你在列表推导式中创建的 lambda 绑定到变量 i ,它最终以 5 结束.因此,当你评估事实之后的 lambdas,它们都绑定到 5 并最终计算 25.同样的事情发生在你的第二个例子中 num .当你在循环内评估 lambda 时,它的 num 没有改变,所以你得到了正确的值.循环后,num 为 5...

I'm guessing that the lambda you're creating in the list comprehension is bound to the variable i which eventually ends up at 5. Thus, when you evaluate the lambdas after the fact, they're all bound to 5 and end up calculating 25. The same thing is happening with num in your second example. When you evaluate the lambda inside the loop it's num hasn't changed so you get the right value. After the loop, num is 5...

我不太确定你要做什么,所以我不确定如何提出解决方案.这个怎么样?

I'm not quite sure what you're going for, so I'm not sure how to suggest a solution. How about this?

def square(x): return lambda : x*x
listOfLambdas = [square(i) for i in [1,2,3,4,5]]
for f in listOfLambdas: print f()

这给了我预期的输出:

1
4
9
16
25

另一种思考方式是 lambda 在创建时捕获"其词法环境.所以,如果你给它 num 它实际上不会解析该值,直到它被调用.这既令人困惑又强大.

Another way to think of this is that a lambda "captures" its lexical environment at the point where it is created. So, if you give it num it doesn't actually resolve that value until its invoked. This is both confusing and powerful.

这篇关于如何创建 lambda 列表(在列表理解/for 循环中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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