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

查看:132
本文介绍了如何创建Python lambdas的列表(在列表解析/ 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



<打印:

Instead, it prints:

25 25 25 25 25

看起来好像lambdas都被赋予了错误的参数。我做错了什么,是否有办法解决它?我在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

相关问题:为什么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

另一种想法是,捕获其词汇环境在它创建的点。因此,如果您给它 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.

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

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