相当于Python生成器的“return”

2024-03-29 05:37:58 发布

您现在位置:Python中文网/ 问答频道 /正文

有时,当将递归函数重写为生成器时,我忽略了return的简洁性。在

"""
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

变成

^{pr2}$

正是这个else让我恼火。我希望有一种方法可以说“yield,这就是它,所以退出函数”。有办法吗?在


Tags: ofreturnthatabbeallcanlength
2条回答

不要错过return,使用它。在

您可以在yield之后return。在

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

另一种方法是在两种情况下使用return,其中第一种情况返回长度为1的序列,第二种情况返回生成器表达式:

^{pr2}$

这种对yield的回避避免了在同一个函数中不能同时使用return <value>和{}的限制。在

(这在您的例子中是有效的,因为您的函数不必是生成器。因为您只迭代结果,所以它也可以返回一个元组。)

没有。当我写"Simple Generators PEP"时,我注意到:

Q. Then why not allow an expression on "return" too?

A. Perhaps we will someday.  In Icon, "return expr" means both "I'm
   done", and "but I have one final useful value to return too, and
   this is it".  At the start, and in the absence of compelling uses
   for "return expr", it's simply cleaner to use "yield" exclusively
   for delivering values.

但这一点一直没有得到重视。在完成之前;-),您可以将生成器的第一部分编写为:

if n == 0:
    yield ""
    return

然后可以删除else:语句并删除其余语句。在

相关问题 更多 >