Search code examples
pythonfunctionnumpyrandomsubtraction

How to subtract or find the differences from this output?


Beginner here, just a week into Python. So what I'm trying to do is figure out how to find the differences from the output I get. Let's say I got [ 5 8 10 8 11] Now I want to 8-5, 10-8, 8-10, 11-8. How do I achieve that? enlighten me.

import numpy as np
import random
ll = list(range(5))

a = np.array(range(5))

b = np.array(random.choices(ll, k=5))

c = np.array([5])

print(a+b+c)

Solution

  • You can try this way by using list comprehension:

    >>> out = [7, 7, 10, 9, 12]  # a normal python list
    >>> out_diff = [ (i-j) for j, i in zip(out[:-1], out[1:]) ]
    >>> out_diff
    [0, 3, -1, 3]
    

    And since you're using numpy, its more easy:

    >>> out[:-1] - out[1:]  # without using functions
    array([ 0, -3,  1, -3])
    

    Or use np.diff:

    >>> np.diff(out)  # assumed 'out' is a numpy array instance
    array([ 0,  3, -1,  3])