python产量和stopiteration在一个循环? [英] python yield and stopiteration in one loop?

查看:101
本文介绍了python产量和stopiteration在一个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成器,我想在其中将初始值和最终值添加到实际内容中,就像这样:

i have a generator where i would like to add an initial and final value to the actual content, it's something like this:

# any generic queue where i would like to get something from
q = Queue()

def gen( header='something', footer='anything' ):
    # initial value header
    yield header

    for c in count():
        # get from the queue
        i = q.get()
        # if we don't have any more data from the queue, spit out the footer and stop
        if i == None:
            yield footer
            raise StopIteration
        else:
            yield i

当然,上面的代码不起作用-我的问题是我希望这样,当队列中没有剩余内容时,我希望生成器吐出footer并提高StopIterator.有什么想法吗?

Of course, the above code doesn't work - my problem is that i would like it such that when there's nothing left in the queue, i want the generator to spit out the footer AND raise the StopIterator. any ideas?

干杯

推荐答案

您似乎过于复杂了:

>>> q = [1, 2, 3, 4]
>>> def gen(header='something', footer='anything'):
        yield header
        for thing in q:
            yield thing
        yield footer


>>> for tmp in gen():
        print(tmp)


something
1
2
3
4
anything

当发电机停止屈服时,

StopIteration将自动升高.这是生成器如何工作的协议的一部分.除非您做的事情非常复杂,否则您根本不需要(也不应该)处理StopIteration.只需yield您要依次从生成器返回的每个值,然后让函数返回.

StopIteration will automatically be raised when a generator stops yielding. It's part of the protocol of how generators work. Unless you're doing something very complex, you don't need to (and shouldn't) deal with StopIteration at all. Just yield each value you want to return from the generator in turn, then let the function return.

这篇关于python产量和stopiteration在一个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆