points = array
def get_nearest_point(x, y, n_points):
dist = []
val = []
j = (x, y)
for z in range(n_points):
for i in range(len(points)):
dist += [Distance(points[i][0],points[i][1],x,y)]
a = dist.index(min(dist))
val.append(points[a])
dist.remove(min(dist))
return val
输出:
get_nearest_point(50,50,3)
[[54,57]]
我想返回类似[[54,57],[56,78],[78,90]]
答案 0 :(得分:1)
您实际上想做的是找到给定数组中最小3个元素的索引。您可以使用numpy.argsort方法轻松完成此操作
无论如何,这是您的numpy代码:
import numpy as np
def get_nearest_point(x, y, n):
dist = [Distance(point[0], point[1], x, y) for point in points]
indices = np.argsort(dist)
return [points[i] for i in indices[:n]]
答案 1 :(得分:1)
欢迎来到该网站!
您编写的代码的问题在于return语句位于循环内部-而是将其移至循环外部。这样,您可以在返回之前将所有三个值附加到val
上。
答案 2 :(得分:0)
在这里我们计算每个点的距离,然后按距离对它进行排序,然后得到前n个点。
def get_nearest_point(x, y, n_points):
points_with_dist = [] # store here pairs (dist, point)
for point in points:
points_with_dist.append((
Distance(point[0], point[1], x, y),
point
))
result_with_dist = sorted(points_with_dist, key=lambda struct: struct[0])[:n_points]
result = [p[1] for p in result_with_dist] # we need only points
return result