python - 将递归生成器对象转换为列表

标签 python recursion iterator python-2.7 generator

我一直在尝试用 Python 实现一个简单的树结构。一棵树从一个有 child 的“根”节点开始,它的每个 child 可能有自己的 child 等等。

现在,我想打印树的所有节点的名称,即将其转换为列表。我试图使用递归性,但不幸的是递归地产生返回生成器对象的子树,我无法将其转换为节点。

有人可以帮助我并指出我在这里做错了什么吗?

class Node:

  def __init__(self,name):
    self.name = name
    self.children = []
    self.parent = None


  def appendChild(self,child):
    self.children.append(child)
    if child is not None:
      child.parent = self


  def listChildren(self):
    yield self
    for child in self.children:
      yield child.listChildren()
    raise StopIteration

# test
r = Node("root")

n = Node("name")
r.appendChild(n)
n.appendChild(Node("name2"))
n.appendChild(Node("name3"))

c = Node("child")
n.appendChild(c)
c.appendChild(Node("child2"))
c.appendChild(Node("child3"))

r.appendChild(Node("name4"))
r.appendChild(Node("name5"))
r.appendChild(Node("name6"))

for child in r.listChildren():
    print child.name

输出:

Traceback (most recent call last):
  File "C:/Users/User/Documents/TreeNode.py", line 40, in <module>
    print child.name
AttributeError: 'generator' object has no attribute 'name'

生成器应该在迭代时被调用,但在我的例子中,r.listChildren() 中的每个子项依次是一个生成器对象。如果这是一个设计缺陷,那么我将不得不寻找另一种生成节点名称列表的方法。

提前致谢!

最佳答案

child.listChildren() 将返回生成器对象而不是实际的子对象。所以你可能想做类似的事情:

def listChildren(self):
  yield self
  for child in self.children:
    for c in child.listChildren():
      yield c
  raise StopIteration # PS: you don't need to do that explicitly

或者,如果您使用 Python 3.3,您可以:

def listChildren(self):
  yield self
  for child in self.children:
    yield from child.listChildren()

关于python - 将递归生成器对象转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275479/

相关文章:

Python - 没有返回逻辑的递归函数

algorithm - 如何递归解决移动受限的汉诺塔?

c++ - 征求关于自定义迭代器的建议我在 C++ 中自定义的容器

c++ - 在 C++ 中遍历成对(或更多)对象

python - 比较两个元组列表

python - 在运行 Django 测试之前加载 SQL 转储

python - rpy2 的 R_HOME 错误

将数组除以自己的列时出现 Python ValueError

java - 数字金字塔,初学递归追踪难吗?

python - 从集合中选择单个项目 : Python