简体   繁体   English

排序向量清单python

[英]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...)? 将这些向量从小到大排序的最快方法是什么(假设距原点的最小距离是列表的第一个成员,第二个最小距离是第二个成员,依此类推)?

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. 我使用平方距离是因为您实际上并没有在任何地方使用该距离,因此计算平方根的成本很高。

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. 这适用于任何n维向量集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM