我有一个生成器,我想在其中向实际内容添加初始值和最终值,如下所示:
# 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
。有任何想法吗?
干杯,
你似乎把这个问题搞得太复杂了:
>>> 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
依次从生成器返回每个值,然后让函数返回。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)