2017-08-15 20 views
1

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

@Prune請看看我的問題,我特意給出了提示該解決方案無效的鏈接。希望你完全讀完這個問題 –

+0

我的歉意。我重新打開了這個。 – Prune

+0

你嘗試過的是什麼沒有奏效?你得到了什麼錯誤? (它爲我工作。) – univerio

回答

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) 
+0

注意:這隻適用於從'產量'的微不足道的用途。如果調用者使用'g.send'或其他發生器特定的函數,則不會。 – o11c