How to sort a lambda tuple

I have tuples:

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

And I also have one coordinate: (8, 7)

Now I need to sort the tuple higher according to the distance between each point of the tuple and one point.

How to do this with sorted()?

+4
source share
2 answers

Essentially, you can calculate the Euclidean distance between your point ptand each tuple in your list. A function numpy.hypotcan do this, although it would be trivial to implement yourself if you want.

>>> 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)]
+7
source

If you don't want to use numpy and want to do it with pure Python,

>>> array = [(1, 2), (3, 2), (1, 4)]
>>> point = [8, 7]
>>> array.sort(key = lambda k: (k[0] - point[0])**2 + (k[1] - point[1])**2)
>>> array
[(3, 2), (1, 4), (1, 2)]
+3
source

Source: https://habr.com/ru/post/1662737/


All Articles