我有一个生成器,我想在实际内容中添加初始值和最终值,它是这样的:
# 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
. 有任何想法吗?
干杯,
2 回答
你似乎过于复杂了这一点:
当发电机停止产生时,将自动引发
StopIteration
. 它做了非常复杂的事情,你根本不应该处理StopIteration
. 只需要yield
依次从发生器返回的每个值,然后让函数返回 .这是一个不需要使用StopIteration的代码,中断就足够了:
结果
现在,这是一个中等复杂的代码,在我看来,我们不能不使用StopIteration . 这对你感兴趣吗?
结果
请注意,此程序仅在
q.get(None)
正确运行,而不是q.get()