python - 如何使用内置函数在列表中找到最接近目标的值?

标签 python

例如,给定

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 目标是从 list 中找到最小化 (a, target)a,例如:

closest_point = find_closest(points, target, dist) # where dist is (a.x-b.x)**2 + (a.y-b.y)**2

我对此感兴趣的原因是因为我发现自己编写了 3 个重复的函数,其中唯一的区别是 dist 函数(并且它们使用不同的字段来计算它)。

最佳答案

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)

关于python - 如何使用内置函数在列表中找到最接近目标的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401708/

相关文章:

python - 如何在easygui python中输出整个循环

python - 控制台中有多少个字符?

python - 我如何在 python 中构建这个 block 矩阵?

python - pip install 在带有 python27 interperter 的 virtualenv 中存在 SSL 问题

python - 如何在 Python 中轻松地为自定义格式化数据创建解析器

python - 使用 PyMC3 进行贝叶斯校准,Kennedy O'Hagan

python - 试图绘制温度

python - python类中私有(private)变量的实际实现

python - 在 python 中将 XGBoost 转换为 PMML

python - 如何在 Python 中获取文件的内容类型? (带网址..)