Create a list by subtracting nth + 1 from the nth value of another list

I need to create a list that returns the difference between the nth and nth + 1 values ​​of another list. Is there a way to simplify the code below to work with any size lists?

mylist = [1,5,15,30,60]

w = mylist[1] - mylist[0]
x = mylist[2] - mylist[1]
y = mylist[3] - mylist[2]
z = mylist[4] - mylist[3]

difflist = [w,x,y,z]

print difflist

And it will return [4,10,15,30]

+4
source share
4 answers

Using zipand list comprehension:

>>> [ a-b for a,b in zip(mylist[1:], mylist[:-1]) ]
=> [4, 10, 15, 30]
Values

#driver

IN : mylist = [1,5,15,30,60]

In case you want the old style to go through the list using it index:

>>> [ mylist[i+1]-mylist[i] for i in range(len(mylist)-1) ]
=> [4, 10, 15, 30]

Although the use is zipbetter than moving it index, because you do not need to generate a list for range, as in the case of python2more Pythonic .

EDIT: The method zipcould also be simplezip(mylist[1:], mylist[:])

+5

:

mylist = [1,5,15,30,60]

def diff(myList):
    return [myList[i+1] - myList[i] for i in range(len(myList)-1)]

l = diff(mylist)
print(l) 

:

[4, 10, 15, 30]
+6
>>>[j-i for i, j in zip(mylist[:-1], mylist[1:])]
=> [4, 10, 15, 30]

numpy. numpy, :

>>>import numpy
>>>numpy.diff(mylist)
=>array([ 4, 10, 15, 30])

>>>list(numpy.diff(mylist))
=>[4,10,15,30]
+4

.

mylist = [1,5,15,30,60]


def diff(mylist):
    return [x - mylist[i - 1] for i, x in enumerate(mylist)][1:]


print(diff(mylist))
# [4, 10, 15, 30]

You must also determine what you want to do when there is one item in the list. In all existing answers, including this one, you will get an empty list as a result if there is only one element in the input list. For example, when mylist = [1], then the output is just an empty list [].

+1
source

Source: https://habr.com/ru/post/1687835/


All Articles