gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:27 25 4
gpt4 key购买 nike

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

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)

关于python - 评估 Python 中的所有嵌套生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42987874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com