Reputation: 23
I have an array with numbers like this, in this case 5 numbers:
a = array([2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707])
I would like to create an array of 10 elements in which the pairwise difference of all the numbers of the array is present. For now i used nested loop for like this:
diffmean = []
for i in range(len(a)-1):
for j in range(i+1, len(a)):
diffmean.append(a[i]-a[j])
Obtaining a list with 10 elements of pairwise difference
[-0.007245185215707384,
0.029778354907735505,
0.018418952746142025,
0.0284510446999775,
0.03702354012344289,
0.02566413796184941,
0.035696229915684885,
-0.01135940216159348,
-0.0013273102077580035,
0.010032091953835476]
there is a "pythonic" way to perform this? without loopfor or nested loop for?
Upvotes: 2
Views: 1080
Reputation: 199
You can use combinations
in build-in itertools
library. Like:
from itertools import combinations
a = [2.88581812, 2.8930633 , 2.85603976, 2.86739916, 2.85736707]
diffmean = []
for b,c in combinations(a, 2):
diffmean.append(b - c)
The second argument of the function is the number of elements you want to combine. The function is order-free and the order-based version is permutations
which returns 20 values in this case.
Upvotes: 2
Reputation: 89
Assuming a
is is numpy array. The below should work, but perhaps a more efficient solution exists as this calculates differences twices
np.expand_dims(a, 1) - a
d[np.tril_indices(a.size, k=-1)]
Upvotes: 1