2017-08-15 40 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