這適用於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