Closures and Loops in Python [duplicate]

柔情痞子 提交于 2019-12-11 04:07:17

问题


Possible Duplicate:
Lexical closures in Python

Suppose I have the following code

callbacks = []
for i in range(10):
  callbacks.append(lambda x: i)

all functions in callbacks will return the final value of i. How can I create callbacks that return the current value for i at creation time?


回答1:


for i in range(10):
  callbacks.append(lambda x = i : x)



回答2:


In [113]: callbacks=[]

In [114]: for i in range(10):
    callbacks.append(lambda x=i:x**2)
   .....:     
   .....:     

In [117]: callbacks[0]()
Out[117]: 0

In [118]: callbacks[1]()
Out[118]: 1

In [119]: callbacks[2]()
Out[119]: 4

In [120]: callbacks[4]()
Out[120]: 16


来源:https://stackoverflow.com/questions/13038779/closures-and-loops-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!