python 中,将lambda函数放进列表,指定访问和循环访问不一样。

我在python 中,将lambda函数放进列表,指定访问和循环访问不一样,求教各位大佬这么为什么,我如果想直接访问,该怎么处理。(指定都是输出1, 循环却正常输出)

代码:

cons = []
for i in range(5):
    temp = {'fun': lambda x: x - i}
    cons.append(temp)

    print(i, temp['fun'](5), cons[i]['fun'](5))
    #print(cons)
print('+' * 30)

print(cons[0]['fun'](5))
print(cons[1]['fun'](5))
print(cons[2]['fun'](5))
print(cons[3]['fun'](5))
print(cons[4]['fun'](5))
print('+' * 30)

for i in range(5):
    print(cons[i]['fun'](5))

输出:

0 5 5
1 4 4
2 3 3
3 2 2
4 1 1
++++++++++++++++++++++++++++++
1
1
1
1
1
++++++++++++++++++++++++++++++
5
4
3
2
1

你lambda中运用啦外部变量i;当你运行完成时i=4;而传入参数x=5; 5-4=1没有什么奇怪的。
cons = []
for i in range(5):
temp = {'fun': lambda x: x - i}
cons.append(temp)

print(i, temp['fun'](5), cons[i]['fun'](5))
#print(cons)

print('+' * 30)

print(cons[0]'fun')
print(cons[1]'fun')
print(cons[2]'fun')
print(cons[3]'fun')
print(cons[4]'fun')
print('+' * 30)

for i in range(5):
print(cons[i]'fun')

0 5 5
1 4 4
2 3 3
3 2 2
4 1 1
++++++++++++++++++++++++++++++
1
1
1
1
1
++++++++++++++++++++++++++++++
5
4
3
2
1

i
Out[21]: 4
明白不

lambad 函数是在执行时才去所含变量的值,相当于你定义了一个代数式,真正要获取结果的时候,代数式才会将此时变量的值带入就得结果返回,
所以才会出现你所描述的结果。
要注意的是:这种编程方式作为平时练习,加深对函数的理解的可以的,在实际的编程中最好不要用,一旦出了问题会隐蔽,处理时会很费时间。如有需要,
可以使用闭包来实现。