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

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


  • 旺盛的绿萝    2020-04-14 10:50:26
  • 阅读 1839    收藏 0    回答 1
  • 邀请
  • 收藏
  • 分享
发送
登录 后发表评论
  • 51testing软件测试圈微信