I have the following array in Python:
points_list = [point0, point1, point2]
where each of points_list is of the type:
class point:
__init__(self, coord, value):
self.coord = numpy.array(coord)
self.value = value
# etc...
And a function:
def distance(x,y):
return numpy.linalg.norm(x.coord - y.coord)
And I have a point point_a defined elsewhere. Now I want to find the point in points_list that's closest to point_a.
Other than a loop, what's the best way to do this in Python?
Have you tried this?
min(points_list, key=lambda x: distance(x, point_a))
To answer a question in comment: lambda is indeed necessary here since function specified as a key argument needs to accept only a single argument.
However, since your point_a is essentially global you could "hard-code" it into the distance function:
>>> point_a = point([1, 2, 3], 5)
>>> def distance(x):
return numpy.linalg.norm(x.coord - point_a.coord)
This way you could pass distance as a key argument skipping lambda altogether.
>>> min(points_list, key=distance)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With