尽量避免forloops来提升Python代码

2024-09-28 01:29:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助来提高我的表现

我得到了一个给定的体积,它是一个由0和1组成的3d矩阵,表示体素。我还得到了一份要点清单。对于体积中的每个体素,我想知道到列表中包含的最近点的距离。下面的代码可能非常耗时

Result_Distances = np.zeros((10,10,10))
Volume = np.ones((10,10,10)) # or any other 3d matrix with 1s or 0s
ListofPoints = [(2,3,2), (2,3,3) ,(2,6,4),(9,6,8)] # or other points

for index, voxel in np.ndenumerate(Volume):

    if voxel == 1:    

            for index2 in ListofPoints:
                distance = np.sqrt((index[0]-index2[0])**2+(index[1]-index2[1])**2+(index[2]-index2[2])**2)
                distances.append(distance)

            Result_Distances[index] = np.amin(distances)

这需要大约1分钟的计算时间,因为我的体积可能非常大(>;1000个体素)。我的分数表更小(大约100分)

有没有一种聪明的方法可以避免循环的耗时?我还尝试了map()函数,但无法以某种方式实现它,因此有了改进

谢谢你的帮助


Tags: orinforindexnp体积resultother

热门问题