Python: 如何使用嵌套for循环将值正确存储在数组中(三循环,三维数组)?

Python: How to use a nested for-loop to properly store values in an array (three loops, three dimensional array)?

使用 Python 3.8.1。和 Numpy 1.19.4

大家好,我对 Python 有点陌生,所以请多多包涵。

我正在执行一个包含三个变量的计算 (a model/simulation),我需要逐个遍历每个变量的相应范围。当我从最终嵌套循环 (k) 中打印每个迭代时,每个范围内的计算和循环似乎都正常工作。但是,在循环后检查 v_ram 数组中的存储值时,这些值不正确,似乎反映了第​​三个 for 循环的最后一次迭代 (k=0:17),其余的由零填充的数组。

phi = np.linspace(0, (14/90)*pi, 8, True)       # 0 to 28 deg in 4 deg steps = 7 + 1 values
theta_step = 20                                 # theta step size = 20 deg
theta = np.linspace(0, (2*pi)-(theta_step*(pi/180)), 18, True)       # 0 to (360-step) deg in 20 deg steps = 17 + 1


# number of simulations/length of resulting v_ram array
n_sim = len(v_sim_mag)*len(phi)*len(theta)
# Initialize the v_ram variable
v_ram = np.zeros((n_sim, 3))

for i in range(len(v_sim_mag)):
    for j in range(len(phi)):
        for k in range(len(theta)):
            v_ram[k] =  [v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),
                        v_sim_mag[i] * math.sin(phi[j]) * math.sin(theta[k]),
                        v_sim_mag[i] * math.cos(phi[j])]
            print("v_ram:", v_ram[k], "v_sim_mag:", v_sim_mag[i], "phi:", phi[j], "theta:", theta[k], "i, j, k:", i, j, k)


print(v_ram)

输出:包括迭代 for 循环打印的最后三行作为示例,然后是数组 v_ram:

的打印

v_ram: [ 4.1858252 -7.25006191 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta: 5.23598775598299 i=, j3, k] 5 v_ram: [ 6.41305626 -5.38119314 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta: 5.585053606381855 i, j, k=1:6[14] v_ram: [ 7.8667781 -2.86327307 15.74478445]
v_sim_mag: 17.83207132052525 phi: 0.4886921905584123 theta: 5.934119456780721 i, j, k=1[14 13]

v_ram_array:
[[ 8.37165039 0. 15.74478445]
[ 7.8667781 2.86327307 15.74478445]
[ 6.41305626 5.38119314 15.74478445]
...
[0.0.0.]
[0.0.0.]
[ 0. 0. 0. ]]

非常感谢任何帮助,欢迎随时讨论我的代码并提供其他建议。

更新

一位朋友提出了另一种效果很好的解决方案:

# number of simulations/length of resulting v_ram array
n_sim = len(v_sim_mag)*len(phi)*len(theta)
# Initialize the v_ram variable
v_ram = np.zeros((len(v_sim_mag), len(phi), len(theta), 6))

for i in range(len(v_sim_mag)):
    for j in range(len(phi)):
        for k in range(len(theta)):
            v_ram[i,j,k] =  [v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),
                        v_sim_mag[i] * math.sin(phi[j]) * math.sin(theta[k]),
                        v_sim_mag[i] * math.cos(phi[j]),
                        i, j, k]

v_ram.shape(2160, 3),但您只分配给 v_ram[k],最多为 17。也许您的意思更像是:

v_ram = np.zeros((n_sim, 3))
v_ram_index = 0

循环核心如下:

v_ram[v_ram_index] =  [
    v_sim_mag[i] * math.sin(phi[j]) * math.cos(theta[k]),
    v_sim_mag[i] * math.sin(phi[j]) * math.sin(theta[k]),
    v_sim_mag[i] * math.cos(phi[j])]
v_ram_index += 1