1

Might seems like a nooby question (myabe it is), but why does python behave like that:

>>>a = []
>>>for i in xrange(5):
...    a.append(lambda: i + 1)

>>>a[0]()
5
>>>a[1]()
5
>>>a[2]()
5
>>>a[3]()
5
>>>a[4]()
5

when there are different functions stored in a:

>>aaa
[<function <lambda> at 0x100499d70>, <function <lambda> at 0x100499e60>, <function <lambda> at 0x100499ed8>, <function <lambda> at 0x100499de8>, <function <lambda> at 0x10049f050>]

or have I missed something really important in python docs?

4

1 回答 1

6

i闭包建立在最终为的值之上4

如果你想保留i在 lambda 中,你可以使用默认变量。

>>>for i in xrange(5):
...    a.append(lambda x=i: x + 1)
于 2013-04-24T13:29:23.100 回答