python yield 和 stopiteration 在一个循环中?
我有一个生成器,我想在其中添加初始值和最终值到实际内容中,它是这样的:
# 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
。有什么想法吗?
干杯,
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
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?
Cheers,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎使这一点变得过于复杂:
当生成器停止产生时,将自动引发
StopIteration
。它是生成器工作协议的一部分。除非您正在做一些非常复杂的事情,否则您根本不需要(也不应该)处理StopIteration
。只需yield
依次从生成器返回的每个值,然后让函数返回即可。You seem to be overcomplicating this quite a bit:
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 withStopIteration
at all. Justyield
each value you want to return from the generator in turn, then let the function return.这是一个不需要使用 StopIteration 的代码,一个中断就足够了:
result
现在,这是一个中等复杂的代码,在我看来,我们不能不使用 StopIteration。您对此感兴趣吗?
结果
请注意,该程序仅使用
q.get(None)
正确运行,而不是q.get()
Here's a code in which use of StopIteration isn't required, a break is enough:
result
Now, here's a moderately complex code in which it seems to me that we can't do without use of StopIteration. Does this interest you ?
result
Note that this program runs correctly only with
q.get(None)
, notq.get()
我来自未来。我推荐
yield from
:输出:
I come from the future. I recommend
yield from
:Output: