给定一个坐标列表,计算每对点之间距离的最有效方法是什么?

2024-10-01 09:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个坐标列表(x,y)。你知道吗

计算每个坐标之间距离的最有效方法是什么?你知道吗

到目前为止,我似乎要做一些事情,比如:

for coord1 in coordinates:
    for coord2 in coordinates:
        if (not_already_done_(coord1,coord2)):
            dist = math.hypot(coord2.x - coord1.x, coord2.y - coord1.y)
            save_dist(dist,coord1,coord2)

没有更快的办法吗?或者至少有更好的写作方法吗?你知道吗


Tags: 方法in距离列表forifdistnot
3条回答

您还可以在类中嵌入distance函数,该函数计算一个坐标和另一个坐标之间的距离。你的课看起来像这样:

from math import hypot

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def distance(self, other):
        dx = self.x - other.x
        dy = self.y - other.y

        return hypot(dx, dy)

然后您可以使用^{}来获得Coordinate对象之间的坐标距离,正如其他人所建议的:

coordinates = [Coordinate(1, 2), Coordinate(2, 3), Coordinate(3, 4)]

distances = [[(c1.getX(), c1.getY()), (c2.getX(), c2.getY()), c1.distance(c2)] for c1, c2 in combinations(coordinates, 2)]

print(distances)

输出:

[[(1, 2), (2, 3), 1.4142135623730951], [(1, 2), (3, 4), 2.8284271247461903], [(2, 3), (3, 4), 1.4142135623730951]]

使用itertools.combinations

from math import hypot
from itertools import combinations

coordinates = [(1, 1), (2, 2), (-2, 5)]

distances = {(a,b): hypot(a[0] - b[0], a[1] - b[1])
             for a, b in combinations(coordinates, 2)}

怎么样:

for n, coord1 in enumerate(coordinates[:-1]):
    for coord2 in coordinates[n+1:]:
        dist = math.hypot(coord2.x - coord1.x, coord2.y - coord1.y)
        save_dist(dist,coord1,coord2)

或:

for n in range(len(coordinates) - 1):
    coord1 = coordinates[n] 
    for m in range(n+1, len(coordinates)):
        coord2 = coordinates[m]
        dist = math.hypot(coord2.x - coord1.x, coord2.y - coord1.y)
        save_dist(dist,coord1,coord2)

相关问题 更多 >