您的位置:首页 > 编程语言 > Python开发

python-生成器,filter的理解

2017-08-08 20:44 155 查看
代码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不再变。因此符合预期
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python filter generator