如何在python中以clokwise方向排列大量2d坐标列表?
我想使用python按顺时针方向排列2d坐标列表。我发现了类似的Q&A,对于小规模的数据来说效果很好。我有一个大约200k点的坐标列表,并试图执行相同的代码,但无法执行如何在python中以clokwise方向排列大量2d坐标列表?,python,map-function,functools,Python,Map Function,Functools,我想使用python按顺时针方向排列2d坐标列表。我发现了类似的Q&A,对于小规模的数据来说效果很好。我有一个大约200k点的坐标列表,并试图执行相同的代码,但无法执行 from functools import reduce import operator import math coords = [(1,1),(3,2),...] # Around 200k points coords = list(dict.fromkeys(coords)
from functools import reduce
import operator
import math
coords = [(1,1),(3,2),...] # Around 200k points
coords = list(dict.fromkeys(coords))
center = tuple(map(operator.truediv, functools.reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2))
final_list = (sorted(coords, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360))
在上述代码中,无法计算中心和程序自动退出。对于保存和计算大量坐标列表,有什么需要更改的吗?一种方法是首先通过角度参数化坐标。 像这样:
centroid = sum(points)/len(points)
angles = map(lambda x: -atan2(x[1], x[0]), points)
tuples_to_sort = zip(angles, points)
sorted_points = map(lambda x: x[1], sorted(tuples_to_sort))
这是因为:
1.角度只是从原点来的角度。
2.我们构造了一个元组列表,其中第一个元素是角度,第二个元素是点。我们这样做是为了以后对它进行排序,而元组排序是在元素对元素的基础上执行的,因此它将根据角度进行排序。
3.我们得到了我们想要的原始点
但是,您的意思是可能存在性能问题,因此您可以尝试使用numpy进行计算。Numpy速度更快,因为它在引擎盖下使用了较低级别的概念,并针对高效的阵列计算进行了优化。下面是上面使用numpy编写的简单版本
import numpy as np
coords = np.array(coords)
center = coords.mean(axis=0)
centered = coords - center
angles = -np.arctan2(centered[:,1], centered[:,0])
sorted_coords = coords[np.argsort(angles)]
result = coords + center
显然,您可以使它更简洁,并为变量提供更合适的名称,但它应该可以工作,并且应该更快一点。它怎么会失败?你能提供一个模拟值吗?我很高兴它有帮助!