Numpy语句代替双forloop

2024-05-19 10:28:59 发布

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

我下面的Python代码非常慢,有没有可能完全用Numpy语句来编写这一部分?你知道吗

    m = len(self.man_list)
    s = len(self.newnew)

self.zeroMatrix = np.zeros((m,s))

    for k in range(m):
        a1 = self.man_list[k][2]
        b1 = self.man_list[k][0]
        a2 = self.man_list[k][3]
        b2 = self.man_list[k][1]
        for f, part in enumerate(self.extra_list):
            x1 = self.extra_list[f][0]
            y1 = self.extra_list[f][2]
            x2 = self.extra_list[f][1]
            y2 = self.extra_list[f][3]

            first = np.array((x1, y1))
            second = np.array((x2, y2))
            third = np.array((a1, b1))
            forth = np.array((a2, b2))


            dist1 = np.linalg.norm(first - third)
            dist2 = np.linalg.norm(second - forth)
            distance = (dist1 + dist2)

            self.zeroMatrix[k][f] = distance

首先,我创建一个带零的矩阵(self.zeroMatrix)。你知道吗

self.man_listself.extra_list包含直线的起点和终点坐标点。 e、 克:

self.man_list = [ [ [1,2], [3,4] ],...]

self.extra_list = [ [ [11,30], [4, 10] ],...]

我得到从第一个列表的每一行到另一个列表的每一行的距离,然后在self.zeroMatrix中注册这个距离值。你知道吗

我非常感谢你的回答!你知道吗


Tags: inselfa2forlena1nparray
1条回答
网友
1楼 · 发布于 2024-05-19 10:28:59

您需要将呼叫矢量化:

man_list = np.array(self.man_list)
extra_list = np.array(self.extra_list)

然后创建所需的子矩阵:

first = extra_list[:, None, ::2]
second = extra_list[:, None, 1::2]
third = man_list[None, :, 2::-2]
fourth = man_list[None, :, 3::-2]

现在,计算最后一个轴的范数,轴2。你知道吗

dist1 = np.linalg.norm(first - third, axis=2)
dist2 = np.linalg.norm(second - fourth, axis=2)
distance = (dist1 + dist2)

现在,你应该在distance中有你想要的矩阵。你知道吗

相关问题 更多 >

    热门问题