## f = [lambda x: x*i for i in range(4)]  （如果将x换成i，调用时候就不用传参数，结果都为3）

>>> f = [lambda x:x*i for i in range(4)]
>>> f[0](1)
3    # 1*3
>>> f[1](1)
3    # 1*3
>>> f[2](1)
3    # 1*3
>>> f[3](1)
3    # 1*3>>> f[0](3)
9    # 3*3
>>> f[1](3)
9    # 3*3
>>> f[2](3)
9    # 3*3
>>> f[3](3)
9    # 3*3

1 def func():
2     fs = []
3     for i in range(4):
4         def lam(x):
5             return x*i
6         fs.append(lam)
7     return fs

>>> def func():
...     fs = []
...     for i in range(4):
...         def lam(x):
...             return x*i
...         fs.append(lam)
...     return fs
...
>>> f = func()
>>> f[0](3)
9
>>> f[2](3)
9
>>> f[1](3)
9

>>> f = [lambda :i*i for i in range(4)]
>>> f[0]()
9
>>> f[1]()
9
>>> f[2]()
9
>>> f[3]()
9 

## f1 = [lambda i=i: i*i for i in range(4)]

>>> f1 = [lambda i=i: i*i for i in range(4)]
>>> f1[0]()
0
>>> f1[1]()
1
>>> f1[2]()
4
>>> f1[3]()
9

1 def func():
2     fs = []
3     for i in range(4)
4         def lam(x=i):   # 即 i=i
5             return x*x    # 即 i*i
6         fs.append(lam)
7     return fs

>>> f1 = [lambda i=i: i*i for i in range(4)]
>>> f1[0](8)
64
>>> f1[1](8)
64
>>> f1[2](8)
64
>>> f1[3](8)
64

## f2 = [lambda x=i: i*i for i in range(4)]

>>> f2 = [lambda x=i: i*i for i in range(4)]
>>> f2[0]()
9
>>> f2[1]()
9
>>> f2[2]()
9
>>> f2[3]()
9
>>> f2[0](7)
9
>>> f2[1](7)
9
>>> f2[2](7)
9

1 def func():
2     fs = []
3     for i in range(4)
4         def lam(x=i):
5             return i*i
6         fs.append(lam)
7     return fs

posted on 2016-11-17 15:12  刘[小]倩  阅读(40540)  评论(0编辑  收藏  举报