递归调用的Python生成器 [英] Python generator with recursive call

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

问题描述

我正尝试使用预生成深度优先搜索在生成器中生成树中的节点.父节点可以有任意数量的子节点,这些子节点存储在列表中.

I am trying to yield nodes in a tree with a generator using a preorder depth first search. The parents node can have any number of children and the children are stored in a list.

我认为这段代码可以工作,但是看起来for循环正在遍历每个孩子,而实际上没有进行递归调用.

I figured this code would work, but it appears that the for loop is iterating over each child without actually going into the recursive call.

def traverse_tree(t):
    yield t.label, t.val
    for child in t.children:
        traverse_tree(child)

有人知道如何处理吗?

推荐答案

如果您查看该函数,则对于每个调用,yield表达式只会被命中一次.因此,您的生成器只会产生一件事.为了让它产生多于一件的事情,您也需​​要从孩子身上屈服:

If you look at the function, for each call, the yield expression only gets hit once. So your generator will only yield one thing. To get it to yield more than one thing, you need to yield from the children too:

def traverse_tree(t):
    yield t.label, t.val
    for child in t.children:
        yield from traverse_tree(child)

这是python 3.3+语法(IIRC).对于早期版本:

This is python 3.3+ syntax (IIRC). For earlier versions:

def traverse_tree(t):
    yield t.label, t.val
    for child in t.children:
        for label, val in traverse_tree(child):
            yield label, val

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

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