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

查看:38
本文介绍了在 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.

推荐答案

丑陋,但只有一种方式:

Ugly, but one way:

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天全站免登陆