yield vs yield from

问题

用法

配合递归使用,遍历树形结构比较方便

E.g:

def parse(tree):
    global count
    count += 1
    for subtree in tree:
        label = subtree.label()
        if label == 'OrderBy':
            print(f"###: {label}")
            yield  subtree
        elif label == 'GroupBy':
            print(f"###: {label}")
            yield  subtree
        elif label in ['AggMetric', 'AggDimension']:
            print(f"###: {label}")
            yield subtree
        elif label == 'Filters':
            print(f"###: {label}")
            yield  subtree
        else:
            yield from parse(subtree)
a = parse(tree)

参考

  1. 从yield 到yield from再到python协程
上一篇:小白新入python坑(2)


下一篇:python第二节课10题