Jon*_*age 42 python yield nested function generator
我有一个功能,可以在下载时产生结果.出于这个问题的目的,让我说我每秒产生一次刺痛,但我想要一个方便函数来包装我的生成器:
import time
def GeneratorFunction(max_val):
for i in range(0,5):
time.sleep(1)
yield "String %d"%i
def SmallGenerator():
yield GeneratorFunction(3)
for s in SmallGenerator():
print s
Run Code Online (Sandbox Code Playgroud)
...为什么不打印出我期待的5根弦?相反,它似乎返回生成器函数:
<generator object GeneratorFunction at 0x020649B8>
Run Code Online (Sandbox Code Playgroud)
如何让这个产生字符串作为普通的生成器函数?
Jon*_*age 29
不敢相信我错过了这个; 答案是简单地返回生成器函数并应用适当的参数:
import time
def GeneratorFunction(max_val):
for i in range(0,max_val):
time.sleep(1)
yield "String %d"%i
def SmallGenerator():
return GeneratorFunction(3) # <-- note the use of return instead of yield
for s in SmallGenerator():
print s
Run Code Online (Sandbox Code Playgroud)
Hib*_*u57 26
您可能必须使用自Python 3.3以来的新yield from版本,称为" 委托生成器 ".
如果我正确地理解了这个问题,我就会遇到同样的问题,并在其他地方找到答案.
我想做这样的事情:
def f():
def g():
do_something()
yield x
…
yield y
do_some_other_thing()
yield a
…
g() # Was not working.
yield g() # Was not what was expected neither; yielded None.
…
yield b
Run Code Online (Sandbox Code Playgroud)
我现在用它代替:
yield from g() # Now it works, it yields x and Y.
Run Code Online (Sandbox Code Playgroud)
我从这个页面得到了答案:Python 3:在Generators - 第1部分(simeonvisser.com)中使用"yield from".