Reputation: 5597
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?
Upvotes: 5
Views: 21166
Reputation: 36555
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
Upvotes: 13
Reputation: 245
You can use key in sorted function.
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(p1, p2):
return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5
sorted_points = sorted(points, key=lambda e: distance(e, target))
Upvotes: 2
Reputation: 8411
See the sort method of list, especially the key argument. It allows you to put a function which returns the key for sorting. So in your example it could be something like this:
def get_ordered_list(x, y):
target_point = Point(x, y)
points.sort(key=lambda p: distance(p, target_point))
assuming that distance(a, b)
returns a distance between points a
and b
. Also note that sort()
sorts the list in place, i.e. modifies the original list. If you want to return a new list which is sorted use the sorted function.
By the way - the class as you defined it is probably not going to work as you expect - the x
and y
fields are class fields. For them to be instance fields you have to define them in the constructor instead:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
Upvotes: 1
Reputation: 11585
You need a function to get the distance between two points, I'll leave this function to you. It will return the distance between two points, one point will be your main point, the other from the list.
Use this function in the sorted
method on the array of points.
Upvotes: 0