-5

I want to find the differences between all values in a numpy array and append it to a new list.

Example: a = [1,4,2,6]
result : newlist= [3,1,5,3,2,2,1,2,4,5,2,4]

i.e for each value i of a, determine difference between values of the rest of the list.

At this point I have been unable to find a solution

Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
nicole
  • 11
  • 1
  • 1

2 Answers2

4

You can do this:

a = [1,4,2,6]
newlist = [abs(i-j) for i in a for j in a if i != j]

Output:

print newlist 
[3, 1, 5, 3, 2, 2, 1, 2, 4, 5, 2, 4]
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
4

I believe what you are trying to do is to calculate absolute differences between elements of the input list, but excluding the self-differences. So, with that idea, this could be one vectorized approach also known as array programming -

# Input list
a = [1,4,2,6]

# Convert input list to a numpy array
arr = np.array(a)

# Calculate absolute differences between each element 
# against all elements to give us a 2D array
sub_arr = np.abs(arr[:,None] - arr)

# Get diagonal indices for the 2D array
N = arr.size
rem_idx = np.arange(N)*(N+1)

# Remove the diagonal elements for the final output
out = np.delete(sub_arr,rem_idx)

Sample run to show the outputs at each step -

In [60]: a
Out[60]: [1, 4, 2, 6]

In [61]: arr
Out[61]: array([1, 4, 2, 6])

In [62]: sub_arr
Out[62]: 
array([[0, 3, 1, 5],
       [3, 0, 2, 2],
       [1, 2, 0, 4],
       [5, 2, 4, 0]])

In [63]: rem_idx
Out[63]: array([ 0,  5, 10, 15])

In [64]: out
Out[64]: array([3, 1, 5, 3, 2, 2, 1, 2, 4, 5, 2, 4])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • what does `None` mean in slicing the `numpy.array( .. )[:,None]` ? – user305883 Apr 28 '19 at 19:33
  • oh found! It is alias of numpy.newaxis - answer here - https://stackoverflow.com/questions/29241056/how-does-numpy-newaxis-work-and-when-to-use-it : it increase dimension of the vector (here, from 1D to 2D) – user305883 Apr 28 '19 at 19:36