递归调用的Python生成器

编程入门 行业动态 更新时间:2024-10-23 00:30:16
本文介绍了递归调用的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生成器

本文发布于:2023-11-17 12:01:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   生成器   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!