在Python中使用Lambda进行递延评估 [英] Deferred evaluation with lambda in Python
问题描述
在一个循环中,我试图将比较两个节点的两个value()推迟到以后。
In a loop, I am trying to defer the comparison the two value()s of two Nodes to a later time.
class Node():
def __init__(self, v):
self.v = v
def value(self):
return self.v
nodes = [Node(0), Node(1), Node(2), Node(3), Node(4), Node(2)]
results = []
for i in [0, 1, 2]:
j = i + 3
results.append(lambda: nodes[i].value() == nodes[j].value())
for result in results:
print result
结果均为True (因为对于所有的λ,i,j == 2,5)。如何将lambda的执行推迟到实际被调用之前,但是具有正确的变量绑定?而且lambda中的表达式不一定都相等……还有更多其他涉及的表达式。
The results are all True (because i,j==2,5 for all the lambdas). How can I defer the execution of the lambda until it is actually called, but with the correct variable bindings? And the expressions in the lambda are not all necessarily equality... there are a bunch of other more involved expressions.
感谢您的帮助!
推荐答案
绑定 i
和 j $的当前值c $ c>而不是让函数在外部范围中显示,可以使用闭包或默认参数值。最简单的方法是在lambda中使用默认参数值:
To bind the current values of i
and j
to the function instead of having it look in the outer scope, you can use either a closure or default argument values. The easiest way to do this is to use default argument values in your lambda:
for i in [0, 1, 2]:
j = i + 3
results.append(lambda i=i, j=j: nodes[i].value() == nodes[j].value())
这里是闭包的样子:
def make_comp_func(i, j):
return lambda: nodes[i].value() == nodes[j].value()
for i in [0, 1, 2]:
j = i + 3
results.append(make_comp_func(i, j))
这篇关于在Python中使用Lambda进行递延评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!