簡體   English   中英

計算列表python中所有元素之間的歐幾里德距離

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

我有一個列表列表。 我想找到所有對與其自身之間的歐幾里德距離並創建一個二維 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM