为让大家独立思考就没有写相应的解释,希望能够理解。
有疑问大家一起来探讨,一起获得成长。
题1
第一种:
def multipliers():
return [lambda x: i * x for i in range(4)]
print([m(2) for m in multipliers()])、
结果:[6, 6, 6, 6]
第二种:yield
def multipliers():
for i in range(4):
yield lambda x: i * x
print([m(2) for m in multipliers()])
结果:[0, 2, 4, 6]
第三种:lambda 匿名函数+闭包
def multipliers():
return [lambda x, i=i: i * x for i in range(4)]
print([m(2) for m in multipliers()])
结果:[0, 2, 4, 6]
第三种演化1:
l = []
for i in range(4):
def f(x, i=i):
return x * i
l.append(f)
ll = []
for i in l:
ll.append(i(2))
print(ll)
结果:[0, 2, 4, 6]
第三种演化2:
def foo(i):
i = i
def f(x):
return x * i
return f
li = []
for i in range(4):
li.append(foo(i))
ll = []
for i in li:
ll.append(i(2))
print(ll)
结果:[0, 2, 4, 6]
题2
def add(n, i):
return n + i
def test():
for i in range(4):
yield i
g = test()
for n in [1, 10]:
g = (add(n, i) for i in g)
print(list(g))
结果:[20, 21, 22, 23]
题3
def demo():
for i in range(4):
yield i
g = demo()
g1 = (i for i in g)
g2 = (i for i in g1)
print(list(g1))
print(list(g2))
结果:
[0, 1, 2, 3]
[]