[英]Can a python generator use recursion?
>>> def gen(num):
... print "inside \n"
... if num < 10:
... gen(num +1)
... yield num
...
>>> x = gen(1)
>>> for i in x:
... print i
...
inside
1
>>>
Why is inside printed only once? 为什么内部仅打印一次? I thought it would get printed many more times.
我认为它将被印刷更多次。
You only created the recursive generator, you never iterated over it . 您仅创建了递归生成器,而从未对其进行迭代 。 If you don't ask a generator for values, it'll never execute.
如果您不要求生成器提供值,它将永远不会执行。
Add a loop and yield the results of the recursive call: 添加一个循环并产生递归调用的结果:
def gen(num):
print "inside"
if num < 10:
for recursive_result in gen(num + 1):
yield recursive_result
yield num
This produces: 这将产生:
>>> def gen(num):
... print "inside"
... if num < 10:
... for recursive_result in gen(num + 1):
... yield recursive_result
... yield num
...
>>> x = gen(1)
>>> for i in x:
... print i
...
inside
inside
inside
inside
inside
inside
inside
inside
inside
inside
10
9
8
7
6
5
4
3
2
1
You are evidently using Python 2, but if you were to use Python 3.3 you can make use of generator delegation and instead of looping use yield from
: 显然,您正在使用Python 2,但如果要使用Python 3.3,则可以使用生成器委派 ,而不是循环使用
yield from
:
def gen(num):
print("inside")
if num < 10:
yield from gen(num + 1)
yield num
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.