在lambda表达式中使用变量的值 [英] Use value of variable in lambda expression

查看:401
本文介绍了在lambda表达式中使用变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的最后一个值,而不是像a []那样运行代码. (即b [0]应该使用x ^ 1,b [1]应该使用x ^ 2,...)

In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)

如何告诉lambda选取i的值而不是变量i本身.

How can I tell lambda to pick up the value of i instead of the variable i itself.

推荐答案

丑陋,但一种方式:

for i in range(4)
    b.append(lambda x, copy=i: x**copy)

您可能更喜欢

def raiser(power):
    return lambda x: x**power

for i in range(4)
    b.append(raiser(i))

(所有代码都未经测试.)

(All code untested.)

这篇关于在lambda表达式中使用变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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