Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a unique list/tuple element given a condition in python

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!

like image 754
attwad Avatar asked Apr 22 '26 18:04

attwad


1 Answers

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

min is a built-in function.

like image 97
alex vasi Avatar answered Apr 24 '26 07:04

alex vasi