Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么这个简单的递归树遍历算法失败了?_Python_Tree_Nested_Generator_Traversal - Fatal编程技术网

Python 为什么这个简单的递归树遍历算法失败了?

Python 为什么这个简单的递归树遍历算法失败了?,python,tree,nested,generator,traversal,Python,Tree,Nested,Generator,Traversal,我已经编写了一个递归算法来遍历Python中的嵌套迭代器。我不明白为什么它能成功地打印出元素,但不能作为生成器生成它们 虽然我已经设法打印出了元素: tree = [[1,2],[3,[['abcde',['f']],'gh']]] def traverse_printing(parent): try: for child in parent: traverse(child) except TypeError:

我已经编写了一个递归算法来遍历Python中的嵌套迭代器。我不明白为什么它能成功地打印出元素,但不能作为生成器生成它们

虽然我已经设法打印出了元素:

tree = [[1,2],[3,[['abcde',['f']],'gh']]]

def traverse_printing(parent): 
     try: 
         for child in parent: 
              traverse(child) 
     except TypeError: 
         print(parent) 

>>> traverse_printing(tree)                                                                                                                                                                                    
1
2
3
a
b
c
...

我正在努力把它变成发电机

def traverse(parent): 
     try: 
         for child in parent: 
              traverse(child) 
     except TypeError: 
         yield parent 
遍历(树)
当前不工作。结果是:

>>> list(traverse(tree))                                                                                                                                                                              
[]
预期结果将是
[1,2,3,'a','b','c','d','e','f','g','h']


为什么会这样?非常感谢

遍历
返回生成器对象。因此,在
遍历
调用中,您必须循环返回的结果并生成每个值,或者使用语句
yield from

for child in parent: 
   yield from traverse(child) 
但是,您当前的解决方案失败,出现了一个
递归错误:超过了最大递归深度
,因为您只捕获了在整数值上出现的迭代(这会引发
类型错误
)。在Python中,在字符串上循环是一个有效的操作,因此需要无限递归调用。因此,您需要检查父项的实际类型:

def traverse(parent): 
  if isinstance(parent, str):
     yield from parent
  elif isinstance(parent, int):
     yield parent
  else: 
     for child in parent: 
        yield from traverse(child) 

list(traverse(tree))
输出:

[1, 2, 3, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

这很有帮助!为了保持它的简单性和类型不可知性,我刚刚添加了另一个except子句
except RecursionError:YOULD parent
,它工作起来很有魅力。谢谢