我一直在研究一个非常时间敏感的项目(不幸的是必须在python中),其中一个广泛使用的函数是一个计算(x,y)元组列表的质心的函数.为了显示:
def centroid(*points):
x_coords = [p[0] for p in points]
y_coords = [p[1] for p in points]
_len = len(points)
centroid_x = sum(x_coords)/_len
centroid_y = sum(y_coords)/_len
return [centroid_x, centroid_y]
Run Code Online (Sandbox Code Playgroud)
哪里
>>> centroid((0, 0), (10, 0), (10, 10), (0, 10))
[5, 5]
Run Code Online (Sandbox Code Playgroud)
这个函数运行得相当快,上面的例子在我的系统上平均完成了1.49e-05秒,但我正在寻找计算质心的最快方法.你有什么想法?
我遇到的其他解决方案之一是执行以下操作(l元组列表在哪里):
map(len(l).__rtruediv__, map(sum, zip(*l)))
Run Code Online (Sandbox Code Playgroud)
它运行在1.01e-05和9.6e-06秒之间,但不幸的是转换为列表(通过包围整个语句list( ... ))几乎使计算时间加倍.
编辑:建议在纯python中欢迎但不是numpy.
EDIT2:刚刚发现,如果为元组列表的长度保留一个单独的变量,那么我的上述实现map在9.2e-06秒内可靠地运行,但仍然存在转换回列表的问题.
EDIT3:
现在我只接受纯蟒蛇的答案,而不是numpy(对那些已经在numpy中回答的人抱歉!)