我在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