可以使用嵌套for循环遍历4维和3维数组,并将结果存储在一个新的4维数组中。示例代码如下:
import numpy as np
four_d = np.random.randint(0, 10, size=(2, 3, 4, 5)) three_d = np.random.randint(0, 10, size=(2, 3, 4))
new_shape = (2, 2, 3, 4, 5) new_array = np.zeros(new_shape)
for i in range(new_shape[0]): for j in range(new_shape[1]): if j == 0: new_array[i, j] = four_d[i, j] if j == 1: new_array[i, j] = three_d[i] if j == 2: new_array[i, j] = four_d[i, j-1] if j == 3: new_array[i, j] = three_d[i]
print(new_array)
输出:
[[[[[5. 7. 9. 9. 2.] [2. 6. 5. 3. 4.] [0. 0. 4. 9. 3.] [3. 8. 1. 3. 3.]]
[[2. 2. 9. 9. 2.] [9. 8. 0. 2. 8.] [0. 2. 4. 4. 1.] [7. 1. 0. 7. 1.]]]
[[[4. 5. 0. 2. 3.] [3. 5. 5. 9. 4.] [4. 9
上一篇:遍历3个字典列表的替代方案
下一篇:遍历5个数据结构的for循环