python - 如何将版本 3.x "yield from"转换为版本 2.7 兼容的版本?

标签 python python-2.7 python-3.x yield-keyword

这适用于Python 3.5。我知道yield from在Python 2.7中不可用。如何使用 python 2.7 实现 depth_first() 函数?

以下解决方案对我没有帮助: 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)

最佳答案

yield from转换为具有普通yield的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)

关于python - 如何将版本 3.x "yield from"转换为版本 2.7 兼容的版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684781/

相关文章:

唯一值的python字典计数

javascript - D3 - 从 JSON 加载数据不起作用

python - 如何根据另一个变量的值调用列表中的元素?

python - Pygame.mixer 模块丢失?

python-3.x - flask:直接写入响应流

python - 向动画散点图添加图例

python - 使用 GRequest 无法实现异步请求

python - 无法在Mac OSX上的python3.6中导入OpenCV,这是依赖性问题吗?

python - 如何在 Python 2.7 中选择 3 个随机数?

python-3.x - 打开Chrome时,Python Selenium Webdriver "Session not created"异常