代码1:
def nums():
i = 3
yield i
while True:
i = i + 2
yield i
def isNot(n):
return lambda x : x % n > 0
def prime():
yield 2
L = nums()
while True:
m = next(L)
yield m
g = lambda x:x%m > 0
L = filter(isNot(m), L)
group = prime()
for i in range(20):
print(next(group))
代码2:
def nums():
i = 3
yield i
while True:
i = i + 2
yield i
def isNot(n):
return lambda x : x % n > 0
def prime():
yield 2
L = nums()
while True:
m = next(L)
yield m
g = lambda x:x%m > 0
L = filter(g, L)
group = prime()
for i in range(20):
print(next(group))
代码设计目的为输出素数
代码1输出符合预期:输出素数;但是代码2却只输出了大于1的奇数
这是为什么?
因为在代码2中 L = filter(ig, L) 中,filter函数返回的是一个生成器(无穷数列),g中的m即为循环中的m。在next时才取出数m = next(L),输出3下一个循环m = next(L),L的定义为
def nums():
i = 3
yield i
while True:
i = i + 2
if g(i):
yield i
也就是
def nums():
i = 3
yield i
while True:
i = i + 2
if i%m >0
yield i
执行完m = next(L)后,此时m已经变为5了
下一个循环时m = next(L),L的定义为
def nums():
i = 3
yield i
while True:
i = i + 2
if g(i):
if g(i):
yield i
此时m已经为7。
然而在代码1中m传入isNot函数中后为n,n不再变。因此符合预期