例如,给出
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
points = [Point(x=1.0, y=1.0), Point(x=2.0, y=2.0), Point(x=5.0, y=5.0)]
target = Point(x=4.5, y=5.0)
closest_point = find_closest(target, points)
我想返回Point(x=5.0, y=5.0)
。理想情况下,我想使用一个内置函数,该函数采用(list, target, comp)
,其中comp
采用(a, b) -> float
,目标是从a
找到这样的list
(a, target)
,例如:
closest_point = find_closest(points, target, dist) # where dist is (a.x-b.x)**2 + (a.y-b.y)**2
我对此感兴趣的原因是因为我发现自己编写了3个重复的函数,唯一的区别是dist
个函数(它们使用不同的字段来计算它)。
答案 0 :(得分:5)
min
函数可以接受一个key
参数,该参数可以用作比较器。在这种情况下,您可以编写一个lambda
来计算每个点到target
的距离。
>>> min(points, key=lambda pt : sqrt((target.x - pt.x)**2 + (target.y - pt.y)**2))
Point(x=5.0, y=5.0)
答案 1 :(得分:0)
您可以尝试以下示例代码:
def find_closest(target, points):
dist = []
for i in points:
dist.append((i.x - target.x)**2 + (i.y - target.y)**2)
min_index = dist.index(min(dist))
return points[min_index]
closest_point = find_closest(target, points)
它给出输出:Point(x=5.0, y=5.0)