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()
?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With