python中的返回生成器
我想做一些类似于以下的事情:python中的返回生成器,python,Python,我想做一些类似于以下的事情: def normal(start): term = start while True: yield term term = term + 1 def iterate(start, inc): if inc == 1: return normal(start) else: term = start while True: yi
def normal(start):
term = start
while True:
yield term
term = term + 1
def iterate(start, inc):
if inc == 1:
return normal(start)
else:
term = start
while True:
yield term
term = term + inc
现在给出了以下错误
SyntaxError: 'return' with argument inside generator
如何通过另一个函数将生成器返回到一个函数?
(注意:这里显示的示例不需要这种功能,但它显示了我需要做的事情)
提前感谢。从Python 3.3开始,您可以使用
yield from normal(start)
,如中所述。在早期版本中,您必须手动迭代其他生成器并生成它生成的结果:
if inc == 1:
for item in normal(start):
yield item
请注意,这不是“返回生成器”,而是一个生成器生成另一个生成器生成的值。您可以使用
yield normal(start)
生成“normal”生成器对象本身,但从您的示例判断,这不是您要查找的对象。生成器表达式中不能有返回
在Python 2.X中,必须手动链接生成器:
def normal(start):
term = start
while True:
yield term
term = term + 1
def iterate(start, inc):
if inc == 1:
for item in normal(start):
yield item
else:
term = start
while True:
yield term
term = term + inc
我假设您知道这两个示例将永远运行:)
FWIW在您最初的示例中,您可以通过生成两个生成器(比如“mormal”和“normal”)然后从iterate函数返回其中一个来清理它。只要你不混合发电机和返回,你可以返回发电机。。。可以说
#using original 'normal'
def abnormal(start, inc):
term = start
while True:
yield term
term = term + inc
def iterate (start, inc):
if inc == 1:
return normal(start)
return abnormal(start, inc)
谢谢@theodex:)它有帮助。谢谢@BrenBarn,它有帮助:)