Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort a tuple with lambda

I have a tuple coords:

[(1, 2), (3, 2), (1, 4)]

And I have also a single coord: (8, 7)

Now I need to sort the tuple above according to the distance between each point in the tuple and the single point.

How to do this with sorted()?

like image 993
Yves Avatar asked Dec 24 '22 23:12

Yves


1 Answers

Essentially you can compute the euclidean distance between your point pt and each of the tuples in your list. The function numpy.hypot can do this, although it would be trivial to implement yourself if you wanted to.

>>> from numpy import hypot
>>> l = [(1, 2), (3, 2), (1, 4)]
>>> pt = [8,7]
>>> sorted(l, key = lambda i: hypot(i[0]-pt[0], i[1]-pt[1]))
[(3, 2), (1, 4), (1, 2)]
like image 52
Cory Kramer Avatar answered Jan 11 '23 22:01

Cory Kramer