Skip to content Skip to sidebar Skip to footer

Calculate Euclidean Distance Between All The Elements In A List Of Lists Python

I have a list of lists. I want to find the euclidean distance between all the pairs and itself and create a 2D numpy array. The distance between itself will have 0 in the place and

Solution 1:

You can use numpy directly to calculate the distances:

pts = [[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]]
x = np.array([pt[0] for pt in pts])
y = np.array([pt[1] for pt in pts])
np.sqrt(np.square(x - x.reshape(-1,1)) + np.square(y - y.reshape(-1,1)))

Solution 2:

There is the excellent answer of BMW. Another possible solution that uses list comprehension is the following:

import numpy as np
a=[[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]]
# generate all the distances with a list comprehension
b=np.array([  ((a[i][0]-a[j][0])**2 + (a[i][1]-a[j][1])**2)**0.5 for i in range(len(a)) for j in range(i,len(a))])

n = len(b)
# generate the indexes of a upper triangular matrix
idx = np.triu_indices(n)
# initialize a matrix of n*n with zeros
matrix = np.zeros((n,n)).astype(int)
# assign to such matrix the results of b
matrix[idx] = b

Post a Comment for "Calculate Euclidean Distance Between All The Elements In A List Of Lists Python"