我有一个问题,需要你的帮助。我有一个类(客户),其中所有客户都存储有各自的 x 和 y 坐标。 我现在想构建一个距离矩阵或二维列表来显示客户之间的距离。
我已经有了距离的工作函数:
# Getting Distances
def get_distance(a,b):
d = [a.getX()- b.getX() , a.getY() - b.getY()]
return sqrt(d[0] * d[0] + d[1] * d[1])
# Distances between Customers:
Distances = []
for i in range(0,nr_customers):
for j in range(0, nr_customers):
get_distance(customer[i],customer[j])
Distances.append(get_distance(customer[i],customer[j]))
当然,到目前为止,只输出了所有距离的一份列表。有人能帮我吗?请不要使用 Numpy 或 Pandas,我们不允许使用它们。
您的代码中缺少的是客户 i 与所有其他客户(包括 i)的距离。您没有将它们作为列表存储在内部循环中。您需要在外循环中定义它。
# Getting Distances
def get_distance(a,b):
return sqrt((a.getX()- b.getX())**2 + (a.getY() - b.getY())**2)
# Distances between Customers:
Distances = []
for i in range(0,nr_customers):
distance_i = []
for j in range(0, nr_customers):
distance_i.append(get_distance(customer[i],customer[j]))
Distances.append(distance_i)
现在您已获得所有客户之间的距离(二维列表)。