在lambda表达式中使用变量的值

2024-09-29 00:13:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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本身呢。在


Tags: lambda代码inforrangeoutappendspits
3条回答

定义工厂

def power_function_factory(value):
    def new_power_function(base):
        return base ** value
    return new_power_function

b = []
for i in range(4):
    b.append(power_function_factory(i))

或者

^{pr2}$

丑陋,但有一个方法:

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

你可能更喜欢

^{pr2}$

(所有代码未经测试。)

b=[]
f=(lambda p:(lambda x:x**p))
for i in range(4):
   b.append(f(i))
for g in b:
   print g(2)

相关问题 更多 >