yield from
- yield from是python3.3新出现的句法
1、替代内层for循环
def chain(*param):
for it in param:
yield from it
s = 'ABC'
t = tuple(range(3))
print(list(s, t))
最终的输出为[‘A’, ‘B’, ‘C’, 0, 1, 2]
- yield from完全替代了内层的for循环
- 示例中首先调用iter(it),从中获取迭代器。因此,it是任何可以迭代的对象。
1.1、利用Node类来表示树结构
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()
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)
- __iter__代表一个python的迭代协议,返回一个迭代器对象,就能迭代。
- __repr__保证打印时的输出格式。
- depth_first返回一个生成器。将参数扁平化处理为一列单独的值。
2、打开双通道
- yield from结构的本质作用是打开双通道,把最外层的调用方与最内层的子生成器连接起来,这样二者就能直接发送和产出值。不用再位于中间的协程中添加大量处理异常的样板代码。