重构列表构建代码

假设你有复杂的代码,通过从空白列表开始并重复附加到它来创建并返回列表:

def create():
    result = []
    # logic here...
    result.append(value) # possibly in several places
    # more logic...
    return result # possibly in several places

values = create()

如果用列表推导替换内部逻辑是不切实际的,你可以将整个函数就地转换为生成器,然后收集结果:

def create_gen():
    # logic...
    yield value
    # more logic
    return # not needed if at the end of the function, of course

values = list(create_gen())

如果逻辑是递归的,则使用 yield from展平结果中包含递归调用的所有值:

def preorder_traversal(node):
    yield node.value
    for child in node.children:
        yield from preorder_traversal(child)