Python 生成器:递归树的正确代码
class Node(object):
def __init__(self, lst):
if type(lst) == list:
self.value = lst[0]
self.children = lst[1:]
else:
self.value = lst
self.children = []
@property
def ChildElements(self):
return [Node(a) for a in self.children]
@property
def GetValue(self):
return self.value
def node_recurse_generator(node):
yield node.value
for n in node.ChildElements:
node_recurse_generator(n)
节点是一种简单的树状数据结构。列表的第一个元素始终是节点的值,其他元素将是子元素。如果 Node 是用列表以外的东西启动的,则该值将是该值,并且子节点将是 [],一个空列表。
a = Node([1,[10,20,30],[100,200,300]])
>>> list(node_recurse_generator(a))
[1]
现在,如果对所有元素都有一个递归迭代器就太好了,但我的生成器只生成第一个元素。为什么会发生这种情况?
class Node(object):
def __init__(self, lst):
if type(lst) == list:
self.value = lst[0]
self.children = lst[1:]
else:
self.value = lst
self.children = []
@property
def ChildElements(self):
return [Node(a) for a in self.children]
@property
def GetValue(self):
return self.value
def node_recurse_generator(node):
yield node.value
for n in node.ChildElements:
node_recurse_generator(n)
Node is a simple tree like data structure. The list's first element is always the value of the Node, further elements will be children. If the Node is initiated with something other than a list, that value will be that, and children will be [], an empty list.
a = Node([1,[10,20,30],[100,200,300]])
>>> list(node_recurse_generator(a))
[1]
Now, it would be great to have a recursive iterator over all the elements, but my generator only yields the first element. Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单地递归调用
node_recurse_generator
是不够的 - 您必须yield
其结果:Simply calling
node_recurse_generator
recursively isn't enough - you have toyield
its results:正如顶部答案的评论中提到的 yak ,您还可以在 Python 之后使用
yield from
3.3.As yak mentioned in the comment of the top answer, you can also use
yield from
after Python 3.3.