How can I get the list item with the min / max property in Python?

I have the following array in Python:

points_list = [point0, point1, point2]

      

where each points_list

is of type:

class point:
    __init__(self, coord, value):
        self.coord = numpy.array(coord)
        self.value = value
# etc...

      

And the 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

which is closest to point_a

.

Except for a loop, what's the best way to do this in Python?

+2


source to share


1 answer


Have you tried this?

min(points_list, key=lambda x: distance(x, point_a))

      

Answer to question in comment : lambda

really needed here, since the function specified as an argument key

to accept only one argument
.

However, since yours point_a

is essentially global, you can "hard-code" it into a function distance

:



>>> point_a = point([1, 2, 3], 5)
>>> def distance(x):
    return numpy.linalg.norm(x.coord - point_a.coord)

      

This way you can pass distance

as a key argument skipping lambda

altogether.

>>> min(points_list, key=distance)

      

+13


source







All Articles