I need to create a list which returns the difference between the nth and nth + 1 values of another list. Is there any way of simplifying the code below to work for 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 this will return [4,10,15,30]
Take a look at this one:
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)
The output is:
[4, 10, 15, 30]
Using zip
and list comprehension
:
>>> [ a-b for a,b in zip(mylist[1:], mylist[:-1]) ]
=> [4, 10, 15, 30]
#driver values
IN : mylist = [1,5,15,30,60]
In case, you want the good old fashioned traversing through the list using its index
:
>>> [ mylist[i+1]-mylist[i] for i in range(len(mylist)-1) ]
=> [4, 10, 15, 30]
Although, using zip
is better than traversing through its index
as you don't need to generate the list for range
as in case of python2
and is more Pythonic .
EDIT : the zip
method can also be just zip(mylist[1:], mylist[:])
>>>[j-i for i, j in zip(mylist[:-1], mylist[1:])]
=> [4, 10, 15, 30]
Or if you might want to consider numpy. Using numpy, the answer is:
>>>import numpy
>>>numpy.diff(mylist)
=>array([ 4, 10, 15, 30])
or
>>>list(numpy.diff(mylist))
=>[4,10,15,30]
Another way to do it.
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 have to also define what you want to do when there is one element in the list. In all the 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 a just empty list []
.
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.