tags:

views:

143

answers:

1

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?

+13  A: 

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)
SilentGhost
+1, you beat me to it
Nadia Alramli
Another Python function I didn't know about :) +1. I guess a loop would only be beneficial if you intend to calculate both min and max at the same time.
Andre Miller
@Andre: I think the better option would be to use `sort` with the same `key` argument and get first and last elements.
SilentGhost
@SilentGhost: Ok.. maybe you want min, max and average :-)
Andre Miller
:-)
SilentGhost
You are still looping, you just have min() do it for you.
ironfroggy
so? do you have some wonder method in mind?
SilentGhost
I didn't know that `min()` accepts a `key` parameter. Thanks.
Nathan Fellman
Is the lambda function really necessary? why can't I just have `key = distance(x, point_a))`? Is it because the key function has to be a function of a single argument?
Nathan Fellman
Thanks for the update regarding lambdas!
Nathan Fellman