我可以使用这样的递归函数创建一个嵌套的迭代器组:
def rprint(n):
for i in range(n):
print('n = %d' % n)
yield rprint(n-1)
Run Code Online (Sandbox Code Playgroud)
然后,举一个简单的例子,我可以手动评估嵌套生成器.
>>> 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
Run Code Online (Sandbox Code Playgroud)
这继续如下......
>>> p1_1_0 = next(p2_1)
>>> p1_1_1 = next(p2_1)
n = 2
n = 2
>>> next(p2_1)# will raise an error
StopIteration
Run Code Online (Sandbox Code Playgroud)
...等
我怎样才能为任意值做到这一点以自动的方式n在rprint?我对中间生成器的变量引用不感兴趣(正如我在示例中所做的那样来说明对象结构).
虽然你可以这样做,但是使用发生器纯粹用于副作用这样做是一件非常奇怪的事情,你可能想重新考虑你的设计.那说:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
214 次 |
| 最近记录: |