日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 距离矩阵_创建距离矩阵?

發布時間:2023/12/15 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 距离矩阵_创建距离矩阵?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。