willmac
willmac

Reputation: 1627

Sort list of vectors python

Assuming you have a list of vectors- such as so:

myListOfVectors=[(10,2),(0,5),(3,2),(8,2),(9,5),(10,5]

What would be the quickest way to sort these vectors from small to large (assuming that the smallest distance from the origin would be the first member of the list and the second smallest distance would be the second member etc...)?

Upvotes: 0

Views: 4501

Answers (2)

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67197

def sqdist(vector)
    return sum(x*x for x in vector)

myListOfVectors.sort(key=sqdist)

Results in:

>>> myListOfVectors
[(3, 2), (0, 5), (8, 2), (10, 2), (9, 5), (10, 5)]

I'm using the squared distance as you don't actually use the distance anywhere, and computing the square root is quite costly.

Upvotes: 5

Jimmy C
Jimmy C

Reputation: 9680

Assuming you are talking about Euclidean distance from origin, here's what I would do:

from math import sqrt

def euclidean_distance(v):
    return sqrt(sum(x**2 for x in v))

myListOfVectors = [(10,2),(0,5),(3,2),(8,2),(9,5),(10,5)]

sorted(myListOfVectors, key=euclidean_distance)

Which returns

[(3, 2), (0, 5), (8, 2), (10, 2), (9, 5), (10, 5)]

This works on any n-dimensional set of vectors.

Upvotes: 1

Related Questions