I have a list of items that have X
and Y
coordinates. Now, there's a method that takes X
and Y
parameters and should return a the list of coordinates ordered from the closest to the farthest based on the given parameters.
Basically, it looks something like this:
class Point:
x = 0.0
y = 0.0
# List of points
points = ...
def get_ordered_list(x, y):
# return 'points' ordered by distance to (x,y)
I'm new to Python so I have pretty much no idea how to order the items. How would I do that?
You can pass a custom function to sort using the key
parameter, for example to sort with the Euclidean norm like this:
def get_ordered_list(points, x, y):
points.sort(key = lambda p: (p.x - x)**2 + (p.y - y)**2)
return points
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