python - 如何计算与列表中点的距离?
问题描述
我有两组列表,A 和 O。它们都有来自 x,yz 坐标的点。我想计算 A 和 B 点之间的距离。我使用了 for 循环,但它只给我一个结果。它应该从结果中给我 8 个数字。我非常感谢有人可以看看。这是我项目的最后一步。
Ax = [-232.34, -233.1, -232.44, -233.02, -232.47, -232.17, -232.6, -232.29, -231.65]
Ay = [-48.48, -49.48, -50.81, -51.42, -51.95, -52.25, -52.83, -53.63, -53.24]
Az = [-260.77, -253.6, -250.25, -248.88, -248.06, -247.59, -245.82, -243.98, -243.76]
Ox = [-302.07, -302.13, -303.13, -302.69, -303.03, -302.55, -302.6, -302.46, -302.59]
Oy = [-1.73, -3.37, -4.92, -4.85, -5.61, -5.2, -5.91, -6.41, -7.4]
Oz = [-280.1, -273.02, -269.74, -268.32, -267.45, -267.22, -266.01, -264.79, -264.96]
distance = []
for xa in A1:
for ya in A2:
for za in A3:
for x1 in o1:
for y1 in o2:
for z1 in o3:
distance += distance
distance = (((xa-x1)**2)+((ya-y1)**2)+((za-z1)**2))**(1/2)
print(distance)
解决方案
其他人已经为您的直接问题提供了解决方案。我还建议您开始使用numpy
并避免所有这些for
循环。Numpy 提供了向量化代码的方法,基本上将所有需要执行的循环卸载到非常高效的 C++ 实现中。例如,您可以用以下矢量化实现替换整个嵌套的 for 循环:
import numpy as np
# Convert your arrays to numpy arrays
Ax = np.asarray(Ax)
Ay = np.asarray(Ay)
Az = np.asarray(Az)
Ox = np.asarray(Ox)
Oy = np.asarray(Oy)
Oz = np.asarray(Oz)
# Find the distance in a single, vectorized operation
np.sqrt(np.sum(((Ax-Ox)**2, (Ay-Oy)**2, (Az-Oz)**2), axis=0))