在Python中迭代期间打印当前值和下一个值

时间:2011-03-31 16:56:42

标签: python iteration

  

可能重复:   Iterate a list as pair (current, next) in Python

在迭代列表时,我想打印列表中的当前项目,以及列表中的下一个值。

listOfStuff = [a,b,c,d,e]
for item in listOfStuff:
    print item, <nextItem>

输出结果为:

a b
b c
c d
d e

4 个答案:

答案 0 :(得分:4)

我发现最简单的方法是:

a = ['a','b','c','d','e']

for i,nexti in zip(a,a[1::]):
    print i,nexti

答案 1 :(得分:0)

listOfStuff = ['a','b','c','d','e']
for i, item in enumerate(listOfStuff[:-1]):
    next_item = listOfStuff[i+1]
    print item, next_item

答案 2 :(得分:0)

怎么样:

for i in range(1, len(listOfStuff)):
    print listOfStuff[i - 1], listOfStuff[i]

答案 3 :(得分:0)

这可能会做你想要的:

def double_iter(iter):
    a = next(iter)
    for item in iter
        yield (a, item)
        a = item

double_iter(original_iter)