本文介绍了通过python中的dictionary.iteritems()检测最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种简单的方式来检测最后一次迭代,而使用 iteritems()
>解决方案
这是的特殊情况。我的建议是创建一个,最后一个项目返回-1:
def注释(gen):
prev_i,prev_val = 0,gen.next()
for i,val in enumerate(gen,start = 1):
yield prev_i,prev_val
prev_i,prev_val = i,val
yield'-1',prev_val
添加code> gen = iter(gen)如果你想要处理序列和生成器。
Is there a simple way to detect the last iteration while iterating over a dictionary using iteritems()
?
解决方案
This is a special case of this broader question. My suggestion was to create an enumerate-like generator that returns -1 on the last item:
def annotate(gen):
prev_i, prev_val = 0, gen.next()
for i, val in enumerate(gen, start=1):
yield prev_i, prev_val
prev_i, prev_val = i, val
yield '-1', prev_val
Add gen = iter(gen)
if you want it to handle sequences as well as generators.
这篇关于通过python中的dictionary.iteritems()检测最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!