【发布时间】:2014-05-26 23:50:58
【问题描述】:
有时,在将递归函数重写为生成器时,我会怀念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
变成
"""
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
是else 困扰着我。我希望有办法说“yield,就是这样,所以退出函数”。有什么办法吗?
【问题讨论】:
-
第一次使用
yield后为什么不加一个return?
标签: python coding-style generator yield