a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
在for循环中,i作为变量传递给lambda,因此当我调用它时,使用i的最后一个值,而不是像处理[]那样运行的代码。(即b[0]应使用x^1,b[1]应使用x^2,…)
我如何告诉lambda取I的值而不是变量I本身呢。在
定义工厂
或者
^{pr2}$丑陋,但有一个方法:
你可能更喜欢
^{pr2}$(所有代码未经测试。)
相关问题 更多 >
编程相关推荐