I have a list of 2-D points
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
and a reference point ref = (x0, y0)
.
I now wish to sort the list candidates
according to their euclidean distances from the reference point ref
, in ascending order.
What is the most Pythonic way of doing so?
Euclidean distance between two points (x1, y1)
and (x2, y2)
is given by:
sqrt((x1 - y1)^2 + (x2 - y2)^2))
To sort the list, you can use the formula, and also you can skip the sqrt
part, as you are just doing comparison, and not calculating the actual distance. i.e:
if x > y then sqrt(x) > sqrt(y)
So, following would work:
ref = (x0, y0)
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
candidates.sort(key=lambda x: (x[0] - ref[0]) ** 2 + (x[1] - ref[1]) ** 2)
Write a function to calculate euclidean distance and use that function with the key
parameter of the list.sort
function.
ref = (x0, y0)
def euclidean(coords):
xx, yy = ref
x, y = coords
return ((x-xx)**2 + (y-yy)**2)**0.5
candidates = [(x1, y1), (x2, y2), (x3, y3), ...]
candidates.sort(key=euclidean)
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