可能重复:
Python: Looping through all but the last item of a list
当您还需要列表中的下一个项目(或任何其他任意项目)时,是否有更好的方法来遍历列表?我用这个,但也许有人可以做得更好......
values = [1, 3, 6, 7 ,9]
diffs = []
for i in range(len(values)):
try: diffs.append(values[i+1] - values[i])
except: pass
print diffs
给出:
[2, 3, 1, 2]
答案 0 :(得分:4)
>>> values = range(10)
>>> values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(values[0:],values[1:])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
答案 1 :(得分:2)
借助pairwise recipe from itertools document
来做什么from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def main():
values = [1, 3, 6, 7 ,9]
diffs = [post - prior for prior, post in pairwise(values)]
print diffs
if __name__ == "__main__":
main()
输出
[2,3,1,2]
答案 2 :(得分:1)
您可以使用
for pos, item in enumerate(values):
try:
diffs.append(values[pos+1] - item)
except IndexError:
pass
虽然在你的情况下(因为你只是在寻找下一个值),你也可以简单地使用
for item,nextitem in zip(values, values[1:]):
diffs.append(nextitem-item)
也可以表示为列表理解:
diffs = [nextitem-item for item,nextitem in zip(values, values[1:])]
答案 3 :(得分:1)
for i, j in zip(values, values[1:]):
j - i
答案 4 :(得分:1)
diff = [values[i+1] - values[i] for i in range(len(values)-1)]
答案 5 :(得分:0)
[y - x for x,y in zip(L,L[1:])]