python 距离矩阵_创建距离矩阵?
我將用純python給出一個方法。
從數學模塊導入sqrt函數:
from math import sqrt
假設您在cords表中有以下坐標:
cords['Boston'] = (5, 2)
定義一個函數來計算兩個給定二維點的歐氏距離:def dist(a, b):
d = [a[0] - b[0], a[1] - b[1]]
return sqrt(d[0] * d[0] + d[1] * d[1])
將結果矩陣初始化為字典:D = {}
for city1, cords1 in cords.items():
D[city1] = {}
for city2, cords2 in cords.items():
D[city1][city2] = dist(cords1, cords2)
D是你的結果矩陣
完整的來源和打印結果如下:from math import sqrt
cords = {}
cords['Boston'] = (5, 2)
cords['Phoenix'] = (7, 3)
cords['New York'] = (8, 1)
def dist(a, b):
d = [a[0] - b[0], a[1] - b[1]]
return sqrt(d[0] * d[0] + d[1] * d[1])
D = {}
for city1, cords1 in cords.items():
D[city1] = {}
for city2, cords2 in cords.items():
D[city1][city2] = dist(cords1, cords2)
for city1, v in D.items():
for city2, d in v.items():
print city1, city2, d
結果:Boston Boston 0.0
Boston New York 3.16227766017
Boston Phoenix 2.2360679775
New York Boston 3.16227766017
New York New York 0.0
New York Phoenix 2.2360679775
Phoenix Boston 2.2360679775
Phoenix New York 2.2360679775
Phoenix Phoenix 0.0
總結
以上是生活随笔為你收集整理的python 距离矩阵_创建距离矩阵?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity学习笔记:预制件Prefab的
- 下一篇: pycharm 类型注释_学习Pytho