简体   繁体   中英

How to subtract the value from the previous value in a list in python?

I am trying to take values in a list, such as [1,2,3] and subtract them from each other. So it would return [-1,-1] because the first value is 1-2 and the second value is 2-3 . How would i achieve this in python? I have tried

[x-y for (x,y) in list]

but this gives a 'need more than one value to unpack error.'

隐藏内置list不是一个好主意,所以我在这里更改了你的变量名

[x - y for x, y in zip(the_list, the_list[1:])]

You can also use a generator created by izipping the list with itself, offset by one index.

from itertools import izip, islice
[x - y for x,y in izip(lst, islice(lst, 1, None))]

This is handy if for some reason lst was itself a generator, or otherwise was not easily examined for its length ahead of time, or you just didn't want to consume it directly.

You can use a list comprehension, but specify a range starting at 1 to the end of the list (or alternatively starting at zero to one minus the length of the list):

lst = [1, 2, 3]
>>> [lst[i - 1] - lst[i] for i in range(1, len(lst))]
[-1, -1]

If you are able to use numpy.diff , this is quite easy:

In [22]: import numpy as np

In [23]: -np.diff([1,2,3])
Out[23]: array([-1, -1])

In [24]: -np.diff([1,2,4,3])
Out[24]: array([-1, -2,  1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM