我想根据欧式距离对坐标值进行重新排序。 例如,我有坐标:
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代码帮助我。我已经计算了距离,但是无法获得带有排序坐标vlaues的列表。
答案 0 :(得分:2)
答案 1 :(得分: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)
答案 2 :(得分: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的示例输出实际上并没有按照他们想要的那样按距离排序。