【问题标题】:How to convert version 3.x "yield from" to something compatible in version 2.7?如何将 3.x 版“从”转换为与 2.7 版兼容的东西?
【发布时间】:2017-08-15 00:07:30
【问题描述】:

这适用于 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)

【问题讨论】:

  • @Prune 请看我的问题,我专门给出了链接,提示该解决方案不起作用。希望您完整阅读问题
  • 我很抱歉。我重新打开了这个。
  • 你尝试了什么没有成功?你得到了什么错误? (它对我有用。)

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


【解决方案1】:

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)

【讨论】:

  • 注意:这仅适用于 yield from 的琐碎用途。如果调用者正在使用g.send 或其他特定于生成器的函数,则不会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多