有效地填充具有许多if语句的多维数组 [英] Fill a multidimensional array efficiently that have many if else statements
问题描述
我想以一种特定且有效的方式填充4dim numpy数组.因为我不太了解,所以我开始用if else语句编写代码,但这看起来并不好,可能很慢,而且我也不确定我是否考虑过每种组合.这是我停止写下的代码:
I want to fill an 4dim numpy array in a specific and efficient way. Because I don't know better I startet to write the code with if else statements, but that doesn't look nice, is probably slow and I also can not be really sure if I thought about every combination. Here is the code which I stopped writing down:
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)互不相同,则条目将为:
So basically what should happen is, that if all variables (x1, x2, x3, x4) are different from each other, the entry would be:
sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3] * ewp[x4]
现在,如果说变量x2和x4相同,则:
Now if lets say the variable x2 and x4 is the same then:
sercnew2[x1, x2, x3, x4] = ewp[x1]* ewp[x2] * ewp[x3]
其他示例可以在上面的代码中看到.基本上,如果两个或多个变量相同,那么我只考虑其中的一个.我希望模式是明确的.否则,请让我注意一下,我将尝试更好地表达我的问题.我很确定,有一种更加智能的方法可以做到这一点.希望您知道得更多,并提前致谢:)
Others examples can be seen in the code above. Basically if two or more variables are the same, then I only consider on of them. I hope the pattern is clear. Otherwise please let me note and I will try to express my problem better. I am pretty sure, that there is a much more intelligent way to do it. Hope you know better and thanks in advance :)
推荐答案
真的希望我已经知道了!这是向量化方法-
Really hoping that I have got it! Here's a vectorized approach -
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)
这篇关于有效地填充具有许多if语句的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!