首页 > 解决方案 > 在列表中转换产量

问题描述

我有这个代码:

def sumto(n, lst):
    if not n and not lst:  # base case 1: empty list = 0
        yield []
        return
    if n < 0 or not lst:  # base case 2: unsolvable
        return
    head, *tail = lst
    for sol in sumto(n-head, tail):  # recursion 1: use first element
        yield [head] + sol
    yield from sumto(n, tail)  # recursion 2: don't use first element

我想将产量转换成一个列表。我该怎么做?所以我只想不使用 yield 但是例如 my_list.append

标签: pythonlistfunctionyield

解决方案


这是等价的:

def sumto(n, lst):
    result = []
    if not n and not lst:
        result.append([])
        return result
    if n < 0 or not lst:
        return result
    head, *tail = lst
    for sol in sumto(n-head, tail):
        result.append([head] + sol)
    result.extend(sumto(n, tail))
    return result

以下规则可以相当普遍地应用于将生成器函数转换为返回 a 的函数list

return
# =>
return result
# also think of an implicit "return" at the end of the generator function

yield x
# => 
result.append(x)

yield from x
# => 
result.extend(x)

但是,通常,您应该努力以相反的方式转换您的代码。生成器是 Python 最好的之一。它们允许您迭代所有元素,而无需将所有元素都保存在内存中,它们只进行生成工作,直到您找到所需的内容。如果你想要一份清单,就打电话list(...)给他们。


推荐阅读