questions about functions inside a function

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Jul 16 08:20:53 EDT 2007


fdu.xiaojf at gmail.com a écrit :
> I want to create a list of function.
> 
> Here is my code:
> In [9]: a = []
> 
> In [10]: for i in range(4):
>    ....:     b = lambda : i**2
>    ....:     a.append(b)
>    ....:
>    ....:
> 
> In [11]: for f in a:
>    ....:     f()
>    ....:
>    ....:
> 9
> 9
> 9
> 9
> 
> What I want is, the value of i should be bounded to the anonymous 
> function. And the output should like this:
> 
> for f in a:
>     print f()
> 0
> 1
> 4
> 9
> 
> How to achieve this?
> 
 >>> a = [lambda i=i:i**2 for i in range(4)]
 >>> for f in a:
...     print f()
...
0
1
4
9
 >>>

HTH



More information about the Python-list mailing list