有效填充具有许多 if else 语句的多维数组

2024-04-06

我想以特定且有效的方式填充 4dim numpy 数组。因为我不太了解,所以我开始用 if else 语句编写代码,但这看起来不太好,可能很慢,而且我也不能真正确定我是否考虑了每种组合。这是我停止写下的代码:

sercnew2 = numpy.zeros((gn, gn, gn, gn))
for x1 in range(gn):
    for x2 in range(gn):
        for x3 in range(gn):
            for x4 in range(gn):
                if x1 == x2 == x3 == x4: 
                    sercnew2[x1, x2, x3, x4] = ewp[x1]
                elif x1 == x2 == x3 != x4:
                    sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x4]
                elif x1 == x2 == x4 != x3:
                    sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3]
                elif x1 == x3 == x4 != x2:
                    sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x2]
                elif x2 == x3 == x4 != x1:
                    sercnew2[x1, x2, x3, x4] = ewp[x2] * ewp[x1]
                elif x1 == x2 != x3 == x4:
                    sercnew2[x1, x2, x3, x4] = ewp[x1] * ewp[x3]
                elif ... many more combinations which have to be considered

所以基本上应该发生的是,如果所有变量(x1、x2、x3、x4)彼此不同,则条目将是:

sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] * ewp[x4]

现在,如果假设变量 x2 和 x4 相同,那么:

sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3]

其他例子可以在上面的代码中看到。基本上,如果两个或多个变量相同,那么我只考虑其中的一个。我希望模式是清晰的。否则请让我注意,我会尽力更好地表达我的问题。我很确定,有一种更智能的方法可以做到这一点。希望您能更好地了解并提前致谢:)


真的希望我能得到它!这是一种矢量化方法 -

from itertools import product

n_dims = 4 # Number of dims

# Create 2D array of all possible combinations of X's as rows
idx = np.sort(np.array(list(product(np.arange(gn), repeat=n_dims))),axis=1)

# Get all X's indexed values from ewp array
vals = ewp[idx]

# Set the duplicates along each row as 1s. With the np.prod coming up next,
#these 1s would not affect the result, which is the expected pattern here.
vals[:,1:][idx[:,1:] == idx[:,:-1]] = 1

# Perform product along each row and reshape into multi-dim array
out = vals.prod(1).reshape([gn]*n_dims)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有效填充具有许多 if else 语句的多维数组 的相关文章

随机推荐