可能重複: 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
可能重複: 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
最簡單的方法,我發現是:
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
如何:
for i in range(1, len(listOfStuff)):
print listOfStuff[i - 1], listOfStuff[i]
這可能做你想做的事:
def double_iter(iter):
a = next(iter)
for item in iter
yield (a, item)
a = item
double_iter(original_iter)
你不需要'枚舉'。 'listOfStuff [: - 1]中的項目:'。 – 2011-03-31 17:12:49