“参考文献enumerate 遍历数组[1]np.diff 函数[2]numpy 适用数组作为索引[3]
import numpy as np
# 适用二维数组表示地图上的六个点
# city_position.shape=(6,2) 表示旅行商经过的路线
city_position=np.array([[1,18],[6,23],[8,64],[7,49],[49,48],[12,36]])
point_x=np.ones((6,1))
point_y=np.ones((6,1))
point_x=city_position[:,0] # 存放路线的横坐标
point_y=city_position[:,1] # 存放路线的纵坐标
# print(point_x)
# print(point_y)
# [ 1 6 8 7 49 12]
# [18 23 64 49 48 36]
# 计算路线的距离
total_distance=np.sum(np.sqrt(np.square(np.diff(point_x)) + np.square(np.diff(point_y))))
print("total_distance",total_distance)
print("np.diff(point_x)",np.diff(point_x))
print("np.diff(point_y)",np.diff(point_y))
# total_distance 144.062319447
# np.diff(point_x) [ 5 2 -1 42 -37]
# np.diff(point_y) [ 5 41 -15 -1 -12]
[1]enumerate遍历数组: https://blog.csdn.net/u013555719/article/details/83578489
[2]np.diff函数: https://blog.csdn.net/u013555719/article/details/83586177
[3]numpy适用数组作为索引: https://blog.csdn.net/u013555719/article/details/83582679
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有