Eli*_*ICA 3 python coding-style yield generator
有时,当重写递归函数作为生成器时,我会想到它的简洁性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
Run Code Online (Sandbox Code Playgroud)
变成
"""
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
Run Code Online (Sandbox Code Playgroud)
这就是else我的错误.我希望有办法说" yield,就是这样,所以退出这个功能".有办法吗?
不要错过return,使用它.
你可以return跟在你后面yield.
def ab_star(n):
if n == 0:
yield ""
return
for s in ab_star(n - 1):
yield "a" + s
yield "b" + s
Run Code Online (Sandbox Code Playgroud)
另一种方法是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' )
Run Code Online (Sandbox Code Playgroud)
这种避免yield避免了您不能同时使用return <value>和yield在同一功能中使用的限制.
(这工作你的情况,因为你的函数不必须是一台发电机.既然你只对结果进行迭代,它也可以返回一个元组.)
没有.当我写"简单的发电机PEP"时,我注意到:
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
然后你可以放弃else:声明,然后休息.