python-生成器,filter的理解

来源:互联网 发布:视频特效编辑软件 编辑:程序博客网 时间:2024/06/06 02:29

代码1:

def nums():    i = 3    yield i    while True:        i = i + 2        yield idef isNot(n):    return lambda x : x % n > 0def 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 idef isNot(n):    return lambda x : x % n > 0def 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 + 2if g(i):        yield i


也就是

def nums():    i = 3    yield i    while True:        i = i + 2if  i%m >0        yield i


执行完m = next(L)后,此时m已经变为5了

下一个循环时m = next(L),L的定义为

def nums():    i = 3    yield i    while True:        i = i + 2if g(i):   if g(i):        yield i


此时m已经为7。


然而在代码1中m传入isNot函数中后为n,n不再变。因此符合预期



原创粉丝点击