如何使用Python中的欧氏距离重新排序坐标值?

问题描述 投票:0回答:3

我想根据欧氏距离重新排序坐标值。例如,我有坐标:

1 2 
2 1 
1 3
1 9
6 9
3 5
6 8
4 5
7 9

我有第一个坐标的欧几里德距离与其他坐标:

使用以下代码:

with open("../data comparision project/testfile.txt") as f:

    # for splitting the text file into to lists of list
    my_list = [[x for x in line.strip().split(' ')] for line in f
    index = 0

    # empty list to store distances.
    euclidean_distance_list = []
    for list_of_item in my_list:
        plot1=my_list[0]
        plot2=my_list[index]
        euclidean_distance=math.sqrt((float(plot1[0])-float(plot2[0]))**2 + (float(plot1[1])-float(plot2[1]))**2)
        index=index+1

    # Out of for loop
    sorted_list=sorted(euclidean_distance_list)
    print(sorted_list)

这会生成以下输出:

[0.0, 1.0, 1.4142135623730951, 3.605551275463989, 4.242640687119285, 7.0, 7.810249675906654, 8.602325267042627, 9.219544457292887]

现在我想根据这些距离重新排序原始坐标值,以便它将是:

1 2
1 3
1 9
2 1
3 5
4 5
6 8
6 9
7 9

任何人都可以帮助我使用python代码。我已经计算了距离但无法获得具有排序坐标值的列表。

python python-3.x euclidean-distance
3个回答
2
投票

您希望基于自定义比较器对列表进行排序。

查看sort函数的key可选参数。您可以提供自定义比较器key

https://docs.python.org/3/howto/sorting.html


1
投票

要填写更多细节 - 假设您已经编写了函数:

def euclidean_distance(a, b):
    # does the math and gives the distance between coordinates a and b.
    # If you got the values some other way - better reorganize the code
    # first so that you have a function like this :)

我们可以使用functools.partial来创建距离给定点的距离函数:

distance_from_a = functools.partial(euclidean_distance, points[0])

然后其余的逻辑构建在Python的本机sorting functionality中:

sorted(points, key=distance_from_a)

0
投票

假设你正在使用numpy,你可以通过做这样的事情来执行自定义排序:

import numpy as np

def euclidian_distance(a, b):
  return np.linalg.norm(a - b)

coords = np.array([[1,2], 
                   [2,1], 
                   [1,3],
                   [1,9],
                   [6,9],
                   [3,5],
                   [6,8],
                   [4,5],
                   [7,9]])

coords = sorted(coords, key=lambda point: euclidian_distance(point, coords[0]))
print(np.matrix(coords)) # matrix is only for formatting for readability purposes

输出:

[[1 2]
 [1 3]
 [2 1]
 [3 5]
 [4 5]
 [1 9]
 [6 8]
 [6 9]
 [7 9]]

解释为什么上述输出与OP不同。这是因为OP的示例输出实际上并没有像他们想要的那样按距离排序。

© www.soinside.com 2019 - 2024. All rights reserved.