Nathan Fellman
Nathan Fellman

Reputation: 127608

How can I get the element of a list that has a minimum/maximum property in Python?

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?

Upvotes: 4

Views: 285

Answers (1)

SilentGhost
SilentGhost

Reputation: 319949

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)

Upvotes: 14

Related Questions