“收益"在此排列生成器中如何工作? [英] How does 'yield' work in this permutation generator?

查看:81
本文介绍了“收益"在此排列生成器中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def perm_generator(lst):
    if len(lst) == 1:
        yield lst
    else:
        for i in range(len(lst)):
            for perm in perm_generator(lst[:i] + lst[i+1:]):
                yield [lst[i]] + perm

这段代码一直困扰着我,因为我不理解yield的相互连接方式.我的理解是yield的行为类似于return,但它会暂时停止直到再次被调用.这些yield是如何工作的?

This code has been bugging me, since I don't understand how the yields connect to each other. My understanding was that yield acts like a return, but it stops temporarily until it is called again. How do these yields work?

推荐答案

查看未使用生成器的版本可能会有所帮助:

It might help seeing a version that doesn't use generators:

def perm_generator(lst):
    res = []
    if len(lst) == 1:
        return [lst]
    else:
        for i in range(len(lst)):
            for perm in perm_generator(lst[:i] + lst[i+1:]):
                res.append([lst[i]] + perm)
    return res

gen = perm_generator([1,2,3])
print gen # prints [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

您可以看到-这不是用收益"将返回"发现并替换".在返回"版本中,我们需要累加结果,而在收益"版本中,我们需要做的就是让"当前排列.

As you can see - this is not a "find and replace" of "return" with "yield". In the "return" version we needs to accumulate the result while in the "yield" version all that needs to be done is to "yield" the current permutation.

这篇关于“收益"在此排列生成器中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆