1

这适用于 Python 3.5。我知道在 python 2.7 中不提供 yield from 。如何depth_first()使用 python 2.7 实现该功能?

以下解决方案对我没有帮助: 将“yield from”语句转换为 Python 2.7 代码

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)
4

1 回答 1

1

转换yield from为具有普通产量的 for 循环。

转换class Node:class Node(object):以确保您获得新式课程。

该代码现在可以在 Python 2.7 中运行。

class Node(object):
 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:
        for n in c.depth_first():
            yield n

# 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)
于 2017-08-15T00:40:18.257 回答