我正在计算在一天的时间表中给出的所有点的总距离。目前,这是通过在numpy矩阵上循环来执行的,按照:
locSequence =要涵盖的点序列
h1和h2 =任意两个连续点
locations =包含任意两点之间距离的简单矩阵
for i in range(len(locSequence)-1):
h1=locSequence[i]
h2=locSequence[i+1]
score += numpyMatrix[locations.loc[h1,'idx'],locations.loc[h2,'idx']+1]
我想知道是否存在编写此代码的pythonic方式,即没有循环。谢谢!
答案 0 :(得分:0)
我将假设locSequence是一个整数列表,范围从0到len(位置),因此任意两个位置loc1
,loc2
之间的距离等于{ {1}}。
示例数据:
locations[loc1, loc2] = locations[loc2, loc1]
然后,我们只是使用广播来获取所有距离:
In [ ]: locSequence = [0, 1, 2, 0] #Travel from point 0 to point 1 to point 2 to point 0.
...: # locations must be a symmetric matrix with all zero diagonal values;
...: # the distance between point x to point x is zero
...: locations = np.zeros((3,3))
...: locations[np.triu_indices(3, 1)] = np.arange(1, 4)
...: locations += locations.T
...: locations
Out[ ]:
array([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])