[英]list of lambdas in python
I have seen this question , but i still cannot get why such simple example does not work: 我已经看到了这个问题 ,但是我仍然无法理解为什么这样简单的示例不起作用:
mylist = ["alice", "bob", "greta"]
funcdict = dict(((y, lambda x: x==str(y)) for y in mylist))
funcdict['alice']("greta")
#True
funcdict['alice']("alice")
#False
funcdict['greta']("greta")
#True
How is it different from: 与以下内容有何不同?
[(y, y) for y in mylist]
Why y
is not evalueated within each step of iteration? 为什么在迭代的每个步骤中都不对
y
求值?
The y
in the body of the lambda
expression is just a name, unrelated to the y
you use to iterate over mylist
. lambda
表达式主体中的y
只是一个名称,与用于迭代mylist
的y
无关。 As a free variable, a value of y
is not found until you actually call the function, at which time it uses whatever value for y
is in the calling scope. 作为一个自由变量,只有在您实际调用该函数后才能找到
y
的值,此时该函数将使用y
在调用范围内的任何值。
To actually force y
to have a value at definition time, you need to make it local to the body via an argument: 要实际上在定义时强制
y
具有一个值,您需要通过一个参数使其局部化:
dict((y, lambda x, y=z: x == str(y)) for z in mylist)
((y, lambda x: x==str(y)) for y in mylist)
y
inside the lambda is not bound at the time of the genration expression defined, but it's bound when it's called; 在定义genration表达式时,lambda内部的
y
不绑定,但在调用时绑定。 When it's called, iteration is already done, so y
references the last item greta
. 调用时,迭代已经完成,因此
y
引用了最后一项greta
。
One way to work around this is to use keyword argument, which is evaluated when the function/lambda is defined: 解决此问题的一种方法是使用关键字参数,该关键字参数在定义函数/ lambda时进行评估:
funcdict = dict((y, lambda x, y=y: x == y) for y in mylist)
funcdict = {y: lambda x, y=y: x == y for y in mylist} # dict-comprehension
or you can use partial
: 或者您可以使用
partial
:
funcdict = {y: partial(operator.eq, y) for y in mylist}
y
is evaluated while the mylist
is iterated. 在迭代
mylist
评估y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.