首页 > 解决方案 > How do i perform operations between elements of a lists in Python using indecies?

问题描述

I have a list of values like this one:

L = [2, 5, 6, 8, 10, 13]

I want to calculate the difference between the first two values and store it into a list using the list indexes. Then, calculate the difference between the second and the third and so on...

I tried a loop like this without success:

[(L[i+1] - L[i]) for i in L]

标签: pythonlist

解决方案


在您的循环中,i保存值,而不是索引,迭代range(len(L))以获取索引(实际上range(len(L) - 1)因为您正在获取下一个值):

>>> [(L[i + 1] - L[i]) for i in range(len(L) - 1)]
[3, 1, 2, 2, 3]

在这种情况下,zip也可以派上用场(在此处迭代值):

>>> [y - x for x, y in zip(L, L[1:])]
[3, 1, 2, 2, 3]

推荐阅读