【发布时间】:2020-08-10 18:32:22
【问题描述】:
【问题讨论】:
-
使用字典
-
如果我没记错的话,你需要一个由最大坐标值定义的大小矩阵。在您的情况下,它将是一个 10x10 矩阵(对称)。这仅在您的坐标是正整数时才有效,如您的示例所示。对于任何其他情况,您需要某种映射数组 imo。
【问题讨论】:
一种解决方案是使用pandas 模块。
scipy.spatial.distance.cdist填写数据
df["[x, y]"]访问从一个点开始的所有距离
iloc 访问特定距离完整代码+插图
# import modules
import pandas as pd
from scipy.spatial.distance import cdist
# input points
points = [[1, 2], [2, 3], [3, 4], [5, 6], [9, 10]]
# Create dataframe
df = pd.DataFrame(cdist(points, points),
columns=[str(p) for p in points],
index=[str(p) for p in points])
print(df)
# [1, 2] [2, 3] [3, 4] [5, 6] [9, 10]
# [1, 2] 0.000000 1.414214 2.828427 5.656854 11.313708
# [2, 3] 1.414214 0.000000 1.414214 4.242641 9.899495
# [3, 4] 2.828427 1.414214 0.000000 2.828427 8.485281
# [5, 6] 5.656854 4.242641 2.828427 0.000000 5.656854
# [9, 10] 11.313708 9.899495 8.485281 5.656854 0.000000
# select column "[2, 3]"
print(df["[2, 3]"])
# [1, 2] 1.414214
# [2, 3] 0.000000
# [3, 4] 1.414214
# [5, 6] 4.242641
# [9, 10] 9.899495
# get distance between point [2 3] and [1 2]
print(df["[2, 3]"].loc["[1, 2]"])
# 1.4142135623730951
希望有帮助
【讨论】:
如果你要求在 numpy 中解决它,你可以使用where 子句。这是一个示例:
import numpy as np
X = np.array([[1,2],[2,3],[3,4],[5,6],[9,10]])
distance_matrix = np.zeros((X.shape[0],X.shape[0]))
# distance matrix
distance_matrix[np.where(X==[1,2])[0][0],np.where(X==[1,2])[0][0]] = 0
distance_matrix[np.where(X==[1,2])[0][0],np.where(X==[2,3])[0][0]] = np.linalg.norm(np.array([1,2]) - np.array([2,3]))
distance_matrix[np.where(X==[2,3])[0][0],np.where(X==[1,2])[0][0]] = np.linalg.norm(np.array([1,2]) - np.array([2,3]))
【讨论】: