python - 将项目添加回可迭代对象( yield /生成器)

标签 python generator yield

我认为这是使用 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 中没有完成 yielding。

这是一个协程,它的运行方式有点像您所说的:

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/

相关文章:

python - 在没有协同例程的情况下编写良好的 Scala(包括使用 Yield 的 Python 示例)

python - 如何包装或嵌入生成器?

python - Flask 中的自定义中止映射/异常

python - 如何检查图像的 channel 顺序?

python - python bcrypt 出现问题,找不到模块

Python 生成器预取?

python - Python Generator 抽象基类没有实现必要的 __del__,这是故意的吗?

python - Keras fit_generator 问题

python - 如何在Python中实现引用调用结构

Python - 理解生成器的发送函数