转换列表中的收益

问题描述 投票:0回答:1

我有此代码:

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转换成列表。我该怎么办?所以我只想不要使用yield,例如my_list.append

python list function yield
1个回答
0
投票

这等效于:

def sumto(n, lst):
    if not n and not lst:  # base case 1: empty list = 0
        return [[]]
    if n < 0 or not lst:  # base case 2: unsolvable
        return []
    result = []
    head, *tail = lst
    for sol in sumto(n-head, tail):  # recursion 1: use first element
        result.append([head] + sol)
    result.extend(sumto(n, tail))
    return result
© www.soinside.com 2019 - 2024. All rights reserved.