在三次迭代中优化python计数

2024-04-19 15:29:42 发布

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

全部

我尝试计算满足以下条件的项目数 房屋id==m,转换日段id==n,邻域函数==m 其中,房屋id由docs['house\u id']表示,日段id由docs['transformed\u dayseg\u id']表示,邻域函数由self.CF/self.TF型/自我.BF. 你知道吗

为此,我按照以下代码执行计数。但是,它太慢了。有没有关于优化python计数代码的想法?你知道吗

def get_mnf_counter(self, docs, dtype):
    x = np.zeros((self.M,self.N,self.K))
    for m in range(self.M):
        for n in range(self.N):
            for k in range(self.K):
                if dtype==1: #checkin
                    x[m, n, k]=sum((np.array(docs['house_id'])==m) & (np.array(docs['transformed_dayseg_id'])==n) & (self.CF==k))
                elif dtype==2: #taxi
                    x[m, n, k]=sum((np.array(docs['house_id'])==m) & (np.array(docs['transformed_dayseg_id'])==n) & (self.TF==k))
                elif dtpe==3: #bus
                    x[m, n, k]=sum((np.array(docs['house_id'])==m) & (np.array(docs['transformed_dayseg_id'])==n) & (self.BF==k))
                else:
                    raise Exception("index of checkin/taxi/bus/ is wrong")
    return x

Tags: inselfiddocsfornprangearray
1条回答
网友
1楼 · 发布于 2024-04-19 15:29:42

你可以像这样使用itertools.product

from itertools import product
...
...

for m, n, k in product(range(self.M), range(self.N), range(self.K)):
   ...

更多的好消息是,你可以优化你的代码甚至更多,像这样

from itertools import product
def get_mnf_counter(self, docs, dtype):
    x = np.zeros((self.M, self.N, self.K))

    if dtype not in (1, 2, 3):
        raise Exception("index of checkin/taxi/bus/ is wrong")

    if dtype == 1:
        value = self.CF
    elif dtype == 2:
        value = self.TF
    else:
        value = self.BF

    house_id = np.array(docs['house_id'])
    dayseg_id = np.array(docs['transformed_dayseg_id'])

    for m, n, k in product(range(self.M), range(self.N), range(self.K)):
        x[m, n, k] = sum((house_id == m) & (dayseg_id == n) & (value == k))

因为你的算法是O(N^3),所以你在这里什么也做不了。你知道吗

相关问题 更多 >