计算列表 python 列表中所有元素之间的欧几里得距离



我有一个列表列表。我想找到所有对和自身之间的欧几里得距离,并创建一个 2D numpy 数组。当对不同时,自身之间的距离将在位置上为 0,值为值。 列表列表示例:[[0, 42908],[1, 3],[1, 69],[1, 11],[0, 1379963888],[0, 1309937401],[0, 1],[0, 3],[0, 3],[0, 77]]我想要的结果是

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 表示差异的值。周期表示结果应遵循矩阵中显示的结果。我需要有关 python 代码的帮助。行和列中的 0、1、2 等数字定义了内部列表索引。

你可以直接使用 numpy 来计算距离:

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

宝马有很好的答案。 使用列表推导的另一种可能的解决方案如下:

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

最新更新