我认为这是使用 yield
的好时机,但我被卡住了。
当出现故障时,我想将项目发送回生成器。我读到这是可能的,所以我真的很想使用我的第一个生成器。
states = ["IL", "NY", "NJ"]
for state in states:
ok = do something
if not ok:
*add state back as the first-to-deal with in the generator*
在这种情况下如何使用生成器?
最佳答案
您可能指的是 coroutine ,它利用了 yield 表达式。它的工作原理有点像这样:
def co_gen(li):
for x in li:
bad = yield x
if bad is not None:
print('ack! {}'.format(bad))
#other error handling
和(人为的)用法:
states = ["IL", "NY", "NJ"]
gen = co_gen(states)
for x in gen:
print('processing state: {}'.format(x))
if x == 'NY':
y = gen.send('Boo, Yankees!')
print( 'processing state after error: {}'.format(y))
# processing state: IL
# processing state: NY
# ack! Boo, Yankees!
# processing state after error: NJ
要点 - 正常的 yield
行为将 None
分配给 bad
。如果它不是 None,则某些内容已被发送
-ed 到生成器中。
当我们发送
一些东西到生成器中时,它恢复操作直到它到达下一个 yield 表达式。所以请记住这一点 - 协程中的上述控制流不是我所说的“标准”,因为在错误 block 中没有完成 yield
ing。
这是一个协程,它的运行方式有点像您所说的:
def co_gen(li):
for x in li:
bad = yield x
while bad is not None:
print('error in generator: {}'.format(bad))
yield
bad = yield bad
gen = co_gen(states)
for x in gen:
print('processing state: {}'.format(x))
if random.choice([0,1]):
gen.send(x) #discard first yield
print( 'error: trying {} again'.format(x) )
# processing state: IL
# error in generator: IL
# error: trying IL again
# processing state: IL
# processing state: NY
# error in generator: NY
# error: trying NY again
# processing state: NY
# processing state: NJ
我们发送
我们的状态返回给生成器,它一直产生它直到我们停止发送它。
关于python - 将项目添加回可迭代对象( yield /生成器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863996/