Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a list of points by distance to a given point?

Tags:

python

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?

like image 321
manabreak Avatar asked Dec 10 '22 22:12

manabreak


1 Answers

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
like image 186
maxymoo Avatar answered Apr 29 '23 22:04

maxymoo