加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

相当于Python生成器的`return`

发布时间:2020-12-20 12:24:19 所属栏目:Python 来源:网络整理
导读:有时,当重写递归函数作为生成器时,我会错过返回的简洁性. """Returns a list of all length n strings that can be made out of a's and/or b's."""def ab_star(n): if n == 0: return [""] results = [] for s in ab_star(n - 1): results.append("a" + s)
有时,当重写递归函数作为生成器时,我会错过返回的简洁性.

"""
Returns a list of all length n strings that can be made out of a's and/or b's.
"""
def ab_star(n):
    if n == 0:
        return [""]

    results = []
    for s in ab_star(n - 1):
        results.append("a" + s)
        results.append("b" + s)

    return results

变成

"""
Generator for all length n strings that can be made out of a's and/or b's.
"""
def ab_star(n):
    if n == 0:
        yield ""

    else:
        for s in ab_star(n - 1):
            yield "a" + s
            yield "b" + s

这就是让我烦恼的其他事情.我希望有一种方法可以说“屈服,这就是它,所以退出这个功能”.有办法吗?

解决方法

不要错过退货,使用它.

您可以在收益后立即返回.

def ab_star(n):
    if n == 0:
        yield ""
        return
    for s in ab_star(n - 1):
        yield "a" + s
        yield "b" + s

另一种方法是在两种情况下都使用return,其中第一种情况返回长度为1的序列,第二种情况返回generator-expression:

def ab_star(n):
    if n == 0:
        return ( "",)
    return ( c+s for s in ab_star(n - 1) for c in 'ab' )

这种避免收益率避免了您不能同时使用return< value>的限制.并且在相同的函数中产生.

(这适用于您的情况,因为您的函数不必是生成器.由于您只迭代结果,它也可以返回元组.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读