开发者

Print current value and next value during iteration in Python [duplicate]

This question already has answers here: 开发者_如何学C Closed 11 years ago.

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜