鍍金池/ 問(wèn)答/Python  HTML/ 生成器工廠函數(shù)循環(huán)終止問(wèn)題

生成器工廠函數(shù)循環(huán)終止問(wèn)題

本人最近在學(xué)習(xí)生成器,遇到一段利用itertools.takewhile構(gòu)造等差數(shù)列生成器工廠函數(shù)的代碼實(shí)例,代碼如下:

import itertools
def aritprog_gen(begin, step, end=None):
    first = type(begin + step)(begin)
    ap_gen = itertools.count(first, step)
    if end is not None:
        ap_gen = itertools.takewhile(lambda n: n < end, ap_gen)
    return ap_gen

問(wèn)題:這個(gè)生成器工廠函數(shù)在end非空時(shí)如何停止產(chǎn)值?

詳細(xì)描述:請(qǐng)問(wèn)當(dāng)end是非空數(shù)值時(shí),若程序運(yùn)行到即將生成次序不小于end+1的臨界點(diǎn),此時(shí)if語(yǔ)句上面的ap_gen正常產(chǎn)值。而繼續(xù)運(yùn)行到下面,takewhile因?yàn)椴粷M足lambda n: n < end停止產(chǎn)值,那停止產(chǎn)值是一個(gè)takewhile對(duì)象,賦值給ap_gen就可以停止迭代產(chǎn)值了?

請(qǐng)明白的前輩幫忙指點(diǎn)一下迷津,感激不盡?。?!

回答
編輯回答
擱淺
a = aritprog_gen(1, 2, 4)
>>> next(a)
1
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> a
<itertools.takewhile object at 0x0000022195ADB9C8>

https://docs.python.org/3/lib...
官網(wǎng)解釋takewhile 就是返回一個(gè)迭代器,所以跟普通迭代器一樣沒值就拋StopIteration異常啦,下面是普通迭代器

>>> a = iter(range(1,4,2))
>>> next(a)
1
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(a, False)
False
>>> a
<range_iterator object at 0x000001D22C9B4F90>

不是一直個(gè)ap_gen賦值,把函數(shù)aritprog_gen改了,a還是itertools.takewhile的對(duì)象

>>> import itertools
>>> def aritprog_gen(begin, step, end=None):
...     first = type(begin + step)(begin)
...     ap_gen = itertools.count(first, step)
...     if end is not None:
...         ap_gen = itertools.takewhile(lambda n: n < end, ap_gen)
...     return ap_gen
...
>>> a = aritprog_gen(1, 2, 4)
>>> def aritprog_gen(begin, step, end=None):
...  return None
...
>>> next(a)
1
>>> a.__next__()
3
>>> a.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
2017年11月10日 22:48