Calculate Euclidean Distance between all the elements in a list of lists python

别说谁变了你拦得住时间么 提交于 2021-01-29 22:05:51

问题


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 the value when the pairs are different. Example of List of Lists:[[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]] The result I want is

  0 1 2 3 4 5 6 7 8
0 0 x x x x x x x x
1   0 x x x x x x x
2     0 x x x x x x 
3       0 x x x x x
4 .................
5 .................
6 .................
7 .................
8 .................

x represents the values of differences. The periods mean the result shall follow as it shows in the matrix. I need help with the code in python. The number of 0,1,2 etc in rows and columns define the inner list index.


回答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)))



回答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


来源:https://stackoverflow.com/questions/59941250/calculate-euclidean-distance-between-all-the-elements-in-a-list-of-lists-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!