Skip to main content
 首页 » 编程设计

python之评估 Python 中的所有嵌套生成器

2025年05月04日11think

我可以使用这样的递归函数来创建一组嵌套的迭代器:

def rprint(n): 
    for i in range(n): 
        print('n = %d' % n) 
        yield rprint(n-1)          

然后举一个简单的例子,我可以手动评估嵌套生成器。

>>> p3 = rprint(3) 
>>> p3 
<generator object rprint at 0x1043b7048> 
>>> p2_0 = next(p3) 
>>> p2_1 = next(p3) 
>>> p2_2 = next(p3) 
n = 3 
n = 3 
n = 3 
>>> next(p3) # will raise an error 
StopIteration 
>>> p1_0_0 = next(p2_0) 
>>> p1_0_1 = next(p2_0) 
n = 2 
n = 2 
>>> next(p2_0)# will raise an error 
StopIteration 
>>> p0_0_0_0 = next(p1_0_0) 
n = 1 
>>> next(p1_0_0)# will raise an error 
StopIteration 
>>> p0_0_1_0 = next(p1_0_1) 
n = 1 
>>> next(p1_0_1)# will raise an error 
StopIteration 

这继续如下......

>>> p1_1_0 = next(p2_1) 
>>> p1_1_1 = next(p2_1) 
n = 2 
n = 2 
>>> next(p2_1)# will raise an error 
StopIteration 

...等等

对于 rprint 中的任何 n 值,我如何自动执行此操作? 我对中间生成器的变量引用不感兴趣(就像我在示例中所做的那样来说明对象结构)。

请您参考如下方法:

虽然您可以做到这一点,但以这种方式纯粹为了副作用使用生成器是一件非常奇怪的事情,您可能需要重新考虑您的设计。也就是说:

def do_the_thing_you_want(generator): 
    # Call list on the generator to force all side effects before running 
    # subgenerators, as done in the question. 
    for subgenerator in list(generator): 
        do_the_thing_you_want(subgenerator)