如何获取生成器函数的多个实例

xst*_*ter 5 python generator

可能重复:
如何克隆Python生成器对象?

假设我有一个生成器'stuff_to_try',我可以逐个尝试它们但是如果我有一个想要通过生成器并且该方法是递归的方法,我想让每个递归获得一个新的生成器,从第一次收益而不是最后一次递归停止的地方.

def solve(something):
    if exit_condition(something):
        return

    next_to_try = stuff_to_try.next()
    while not if_works(next_to_try):
        next_to_try = stuff_to_try.next()
    solve(do_something(something))
Run Code Online (Sandbox Code Playgroud)

当然我可以在递归函数中定义stuff_to_try但是有更好的方法吗?有没有相当于stuff_to_try.clone().reset()或什么?

Len*_*bro 3

在函数中定义生成器:

def stuff_to_try():
    return (i for i in [stuff, to, try])
Run Code Online (Sandbox Code Playgroud)

然后每次你想要一个新的生成器时,只需调用该函数即可。

def solve(something):
    if exit_condition(something):
        return

    for next_to_try in stuff_to_try():
        if_works(next_to_try):
            break
    solve(do_something(something))
Run Code Online (Sandbox Code Playgroud)

如果我正确地阅读了你的问题,你真正想要的是这样的:

def solve(something):
    if exit_condition(something):
        return

    for each in [stuff, to, try]:
        if_works(each):
            break
    solve(do_something(something))
Run Code Online (Sandbox Code Playgroud)