Python 替换嵌套 for 循环

标签 python numpy

我有以下代码:

import itertools
import numpy as np

t = np.random.rand(3,3,3) 

def foo(T):    

    res = np.zeros((3,3,3))
    
    for a in range(3):
        for b in range(3):
            for c in range(3):
                idx = [a,b,c]
                combinations = list(itertools.permutations(idx, len(idx)))
                idx_arrays = tuple(np.array(idx) for idx in zip(*combinations))     
                res[a, b, c] = (1.0/len(combinations))*np.sum(T[idx_arrays])
        
        
    return res

sol = foo(t)

上面的代码应该相当于:

for a in range(3):
        for b in range(3):
            for c in range(3):
                res2[a,b,c] = (1.0/6)*(
                                        t[a,b,c]
                                        + t[a,c,b]
                                        + t[b,a,c]
                                        + t[b,c,a]
                                        + t[c, a, b]
                                        + t[c,b,a]
                                        )

为了使代码更快,我想替换外部的for循环。这可以做到吗?理想情况下,这应该在不使用 numpy 的 einsum 方法的情况下实现。

最佳答案

您可以通过不进行重复计算来开始改进:

def foo(t):
    res = np.zeros_like(t).astype(t.dtype)
    A, B, C = t.shape
    for a in range(A):
        for b in range(a, B):
            for c in range(b, C):
                r = (1.0 / 6) * (
                    t[a, b, c]
                    + t[a, c, b]
                    + t[b, a, c]
                    + t[b, c, a]
                    + t[c, a, b]
                    + t[c, b, a]
                )
                res[a, b, c] = r
                res[a, c, b] = r
                res[b, a, c] = r
                res[b, c, a] = r
                res[c, a, b] = r
                res[c, b, a] = r
    return res

关于Python 替换嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76226149/

相关文章:

python - 将 CSV 值读入列表字典的大多数 Pythonic 方式

python - 计算存储在列表中的二维 numpy 数组的平均值

python - 使用编译使我的程序更快

__le__、__ge__ 的 python 错误?

python - 如何使用 python 脚本从数据库中检索具有列名的值?

python - Python中根据特定列分解数据集

python - 将一键编码数据帧列转换为一列

arrays - 通过 numpy 从另一个列表中的向量中减去列表中的每个向量

python - Pygame键盘输入问题

python - TensorFlow 1.0.0 的prepare_attention API 相当于tensorflow 1.2.0