Python: access to iterator-object in for-loops
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)
Edit: I wander if there is a way to get access to the loop-ite开发者_如何学编程rator other than defining it explicitly as in my example.
Thanks!
data = list(range(10))
it = iter(data)
for i in it:
if i==5:
j = it.next()
print "Consuming {0},{1}".format(i,j)
else:
print i
results in
0
1
2
3
4
Consuming 5,6
7
8
9
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
精彩评论