这适用于Python 3.5,我理解yield是不可用于python 2.7的。我如何使用python 2.7实现depth_first()
函数?如何将版本3.x“yield from”转换为版本2.7中兼容的内容?
下面的解决方案并没有帮助我: Converting "yield from" statement to Python 2.7 code
class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
# Example
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for ch in root.depth_first():
print(ch)
这是预期的输出:
Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
@Prune请看看我的问题,我特意给出了提示该解决方案无效的链接。希望你完全读完这个问题 –
我的歉意。我重新打开了这个。 – Prune
你尝试过的是什么没有奏效?你得到了什么错误? (它为我工作。) – univerio