Print current value and next value during iteration in Python [duplicate]
Possible Duplicate: Iterate a list as pair (current, next) in Python
While iterating a list, I want to print the current item in the list, plus the next value in the list.
listOfStuff = [a,b,c,d,e]
for item in listOfStuff:
print item, <nextItem>
The output would be:
a b
b c
c d
d e
The easiest way I found was:
a = ['a','b','c','d','e']
for i,nexti in zip(a,a[1::]):
print i,nexti
listOfStuff = ['a','b','c','d','e']
for i, item in enumerate(listOfStuff[:-1]):
next_item = listOfStuff[i+1]
print item, next_item
How about:
for i in range(1, len(listOfStuff)):
print listOfStuff[i - 1], listOfStuff[i]
This might do what you want:
def double_iter(iter):
a = next(iter)
for item in iter
yield (a, item)
a = item
double_iter(original_iter)
精彩评论