可能重複:
Python: Looping through all but the last item of a listPython的方法列表中的項目荏苒
說,我想通過列表進行迭代。每次迭代我都想用當前和下一個項來計算某些東西。我可以做類似
mylist = [1, 2, 3, 4]
for i in range(len(mylist)):
try:
compute(mylist[i], mylist[i+1])
except IndexError:
compute(mylist[i])
我還可以做
mylist = [1, 2, 3, 4]
for num in mylist:
try:
compute(num, mylist[mylist.index(num)+1])
except IndexError:
compute(num)
這些都不顯得特別好。有沒有更pythonic的做法呢?
您可以嘗試使用'pairwise'從食譜[itertools文檔](http://docs.python.org/2/library/itertools.html#recipes)。 – Wessie
@Wessie:這正是他應該做的......你應該把它變成一個答案。 –
爲什麼在最後一次迭代中只有一個參數調用'compute'? – Eric