我在 Python 中有以下数组:
points_list = [point0, point1, point2]
其中每个 points_list
都是以下类型:
class point:
__init__(self, coord, value):
self.coord = numpy.array(coord)
self.value = value
# etc...
还有一个函数:
def distance(x,y):
return numpy.linalg.norm(x.coord - y.coord)
我在别处定义了一个点point_a
。现在我想在 points_list
中找到最接近 point_a
的点。
除了循环,在 Python 中执行此操作的最佳方法是什么?
最佳答案
你试过吗?
min(points_list, key=lambda x: distance(x, point_a))
在评论中回答一个问题:lambda
在这里确实是必要的,因为function specified as a key
argument needs to accept only a single argument .
但是,因为您的 point_a
本质上是全局的,您可以将它“硬编码”到 distance
函数中:
>>> point_a = point([1, 2, 3], 5)
>>> def distance(x):
return numpy.linalg.norm(x.coord - point_a.coord)
通过这种方式,您可以将 distance
作为关键参数传递,从而完全跳过 lambda
。
>>> min(points_list, key=distance)
关于python - 如何在 Python 中获取具有最小/最大属性的列表元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1460512/