51Testing软件测试论坛

标题: python 中,将lambda函数放进列表,指定访问和循环访问不一样 [打印本页]

作者: 测试积点老人    时间: 2020-9-17 09:59
标题: python 中,将lambda函数放进列表,指定访问和循环访问不一样
我在python 中,将lambda函数放进列表,指定访问和循环访问不一样,求教各位大佬这么为什么,我如果想直接访问,该怎么处理。(指定都是输出1, 循环却正常输出)
代码:
  1. cons = []
  2. for i in range(5):
  3.    temp = {'fun': lambda x: x - i}
  4.    cons.append(temp)

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

  8. print(cons[0]['fun'](5))
  9. print(cons[1]['fun'](5))
  10. print(cons[2]['fun'](5))
  11. print(cons[3]['fun'](5))
  12. print(cons[4]['fun'](5))
  13. print('+' * 30)

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

  16. 输出:

  17. 0 5 5
  18. 1 4 4
  19. 2 3 3
  20. 3 2 2
  21. 4 1 1
  22. ++++++++++++++++++++++++++++++
  23. 1
  24. 1
  25. 1
  26. 1
  27. 1
  28. ++++++++++++++++++++++++++++++
  29. 5
  30. 4
  31. 3
  32. 2
  33. 1
复制代码



作者: 海海豚    时间: 2020-9-18 09:43
https://ask.csdn.net/questions/1063329?sort=votes_count  看下这个
作者: 郭小贱    时间: 2020-9-18 10:17
参考1楼的链接即可~
作者: bellas    时间: 2020-9-18 10:21
参考下这个链接https://ask.csdn.net/questions/1063329?sort=votes_count
作者: qqq911    时间: 2020-9-18 10:36

https://ask.csdn.net/questions/1063329?sort=votes_count  看下这个
作者: jingzizx    时间: 2020-9-18 13:20
参考楼上链接吧




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2