Python:访问for循环中的迭代器对象 [英] Python: access to iterator-object in for-loops

查看:255
本文介绍了Python:访问for循环中的迭代器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在循环内部显式地执行循环迭代器。有没有比这更好的方法:

I want to step the loop iterator explicitly inside the loop. Is there a 'nicer' way to do this than:

idx = iter(range(0, 10))

for i in idx:
   print i

   if i == 5:
      print "consuming %i in step %i" % (next(idx), i)

编辑:我徘徊是否有办法访问循环迭代器,而不是像在我的例子中那样明确地定义它。

I wander if there is a way to get access to the loop-iterator other than defining it explicitly as in my example.

谢谢!

推荐答案

您可以定义一个生成器来单独或成对地从迭代器中生成元素。这使得for-loop变得更加简单,同时隔离了生成器中的过滤逻辑。

You could define a generator to yield elements from the iterator singly or in pairs. This keeps the for-loop nice and simple, while isolating the filtering logic in the generator.

def my_filter(iterable):
    result=[]
    for i in iterable:
        result.append(i)
        if i==5:
            continue
        yield result
        result=[]        

idx = iter(range(0, 10))

for i in my_filter(idx):
    print i

这篇关于Python:访问for循环中的迭代器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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