生成器可以递归吗? [英] Can generators be recursive?

查看:93
本文介绍了生成器可以递归吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我天真地尝试创建一个递归生成器.没用这就是我所做的:

I naively tried to create a recursive generator. Didn't work. This is what I did:

def recursive_generator(lis):
    yield lis[0]
    recursive_generator(lis[1:])

for k in recursive_generator([6,3,9,1]):
    print(k)

我所得到的只是第一项6.

All I got was the first item 6.

有没有办法使这种代码起作用?实质上是在递归方案中将yield命令传递到上面的级别吗?

Is there a way to make such code work? Essentially transferring the yield command to the level above in a recursion scheme?

推荐答案

尝试一下:

def recursive_generator(lis):
    yield lis[0]
    yield from recursive_generator(lis[1:])

for k in recursive_generator([6,3,9,1]):
    print(k)

我应该指出,由于您的函数存在错误,因此无法正常工作.它可能应该包含lis不为空的检查,如下所示:

I should point out this doesn't work because of a bug in your function. It should probably include a check that lis isn't empty, as shown below:

def recursive_generator(lis):
    if lis:
        yield lis[0]
        yield from recursive_generator(lis[1:])

如果您使用的是python 2.7并且没有yield from,则

In case you are on Python 2.7 and don't have yield from, check this question out.

这篇关于生成器可以递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆