简体   繁体   中英

Finding the differences between integers in the list

After much tinkering, I have finally come up with a piece of code that takes the differences between each of the integers in the same list, and dumps them into a new list. Here's my code:

ints = [3, 5, 9, 15, 36]
difs = []
h = 0

while h < len(ints) - 1:    
    difs.append(ints[1 + h] - ints[0 + h])
    h = h + 1
print difs  

When run, the list 'difs' contains [2, 4, 6, 21] (ie the differences between the integers in the 'int' list.

My question: is there any even simpler function--perhaps in numpy--that does this automatically?

There is a function in numpy : numpy.diff() .

>>> import numpy
>>> numpy.diff([3, 5, 9, 15, 36])
array([ 2,  4,  6, 21])

Using list comprehension with zip :

>>> ints = [3, 5, 9, 15, 36]
>>> [b-a for a, b in  zip(ints, ints[1:])]
[2, 4, 6, 21]

Yes, There is a function diff() in numpy. It can be used like this...

ints = [3, 5, 9, 15, 36]
x = numpy.array(ints)

numpy.diff(x)

output:

[2, 4, 6, 21]  

You can also use the same function to get the difference between two lists using axis parameter in the function.

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