How to loop through all but the last item of a list?

I would like to loop through a list checking each item against the one following it.

Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.

Note

freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.

Apologies for the confusion.


for x in y[:-1]

如果y是一个生成器,那么以上将不起作用。


将序列项目与以下内容进行比较的最简单方法:

for i, j in zip(a, a[1:]):
     # compare i (the current) to j (the following)

If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    b.next()
    return izip(a,b)

for current_item, next_item in pairwise(y):
    if compare(current_item, next_item):
        # do what you have to do

If you need to compare the last value to some special value, chain that value to the end

for current, next_item in pairwise(chain(y, [None])):
链接地址: http://www.djcxy.com/p/53472.html

上一篇: Python的生成器和迭代器之间的区别

下一篇: 如何遍历列表中的最后一项而不是所有项目?