views:

500

answers:

1

Hi!

How do I get a tuple/list element given a condition in python? This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.

here could be an example:

Consider a tuple containing 2D points coordinates like this:

points = [[x1, y1],[x2, y2],[x3, y3], ...]

And I would like to get the point that minimizes the euclidean distance given an arbitrary point (say [X, Y] for instance, my point is : it is not contained in the list!)

def dist(p1, p2):
    return sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2)
pointToCompare2 = [X, Y]

Anyone having a freaky one liner(or not) for that? Thanks!

+10  A: 
min(points, key=lambda x: dist(pointToCompare2, x))

min is a built-in function.

alex vasi