Python中Yield的替代方案

2 投票
1 回答
3165 浏览
提问于 2025-04-18 07:40

有没有一种其他的方法(即使写起来更长一些)来写这个代码中的yield部分?我对这个函数不太熟悉,想保持简单。

for i in range(0, len(lstInput) - intCount + 1):
    if intCount == 1:
        yield [lstInput[i]]
    else:
        current = lstInput[i]
        remainder = lstInput[i+1:]
        for rest in yieldLotto(remainder, intCount - 1):
            yield [current] + rest

1 个回答

3

另一种选择是把循环放到你调用的程序里,或者把它改成返回一个列表。不过这样的话,所有的数据都会存到内存里。

def foo():
    return_list = []
    for i in range(0, len(lstInput) - intCount + 1):
        if intCount == 1:
            return_list.append([lstInput[i]])
        else:
            current = lstInput[i]
            remainder = lstInput[i+1:]
            for rest in yieldLotto(remainder, intCount - 1):
                return_list.append([current] + rest)
    return return_list

老实说,我觉得使用 yield 更好,而且这是 Python 中一个很重要的特性。我建议你去学习一下。

撰写回答