Python yield程序运行

时间:2017-08-09 15:38:34

标签: python yield

以下程序的结果是 2 step 3 step 5 step 7 step

收益如何运行?收益率是按n还是generator收取的? 为什么9号不回答结果(2 step 3 step 5 step 7 step step)? 你能解释一下这个程序是如何运行的吗?

def _odd_iter():
    n = 1
    while True:
        n = n+2
        yield n

def _not_divisible(n):
    return lambda x:x%n >0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        print('step')
        n = next(it)
        yield n
        it = filter(_not_divisible(n),it)

c = primes()
for i in c:
    if i<10:
        print(i)
    else:
        break

1 个答案:

答案 0 :(得分:1)

程序正在执行的操作取决于最后五行中的for - 循环。循环正在消耗由生成器c生成的素数(2,3,5,7,11,13 ......)。

c不会产生9,因为9不是素数(它可以被3整除)。

程序没有打印11,13,...因为当for变为11(11不小于10)时退出i - 循环。