我开始学习C ++,并且在python方面有更多经验。
我有以下用python编写的代码,该代码从3D数组返回Z维平均值的2D数组
import numpy as np
def mean_py_st_ov(array):
x = array.shape[1]
y = array.shape[2]
values = np.empty((x,y), type(array[0][0][0]))
for i in range(x):
for j in range(y):
values[i][j] = ((np.mean(array[:, i, j])))
return values
我正在处理以下代码,以返回3d数组的维数的均值,但到现在为止。.我正在努力尝试一次获取每个维中的i-j元素。
// C++ program to print elements of Three-Dimensional
// Array
#include<iostream>
using namespace std;
int main()
{
// initializing the 3-dimensional array
int x[3][2][2] =
{
{ {0,1}, {2,3} },
{{4,5}, {6,7}},
{{8,9}, {10,11} }
};
// output each element's value
for (int k = 0; k < 3; ++k)
{
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
cout << "Element at x[" << k << "][" << i
<< "][" << j << "] = " << x[k][i][j]
<< endl;
}
}
}
return 0;
}
我收到以下输出
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[1][0][0] = 4
Element at x[1][0][1] = 5
Element at x[1][1][0] = 6
Element at x[1][1][1] = 7
Element at x[2][0][0] = 8
Element at x[2][0][1] = 9
Element at x[2][1][0] = 10
Element at x[2][1][1] = 11
我要说的是... 1array的第一个元素与第二个数组的第一个元素,然后1array的第二个元素与2array的第二个元素。我遍历网络的所有示例都仅以i,j,k的方式进行迭代,并且它按我不想要的顺序打印所有元素,因为我需要获取3D数组中Z轴的均值。 / p>
我需要以下输出:
Element at x[0][0][0] = 0
Element at x[1][0][0] = 4
Element at x[2][0][0] = 8
Element at x[0][0][1] = 1
Element at x[1][0][1] = 5
Element at x[2][0][1] = 9
Element at x[0][1][0] = 2
Element at x[1][1][0] = 6
Element at x[2][1][0] = 10
Element at x[0][1][1] = 3
Element at x[1][1][1] = 7
Element at x[2][1][1] = 11
能帮我吗!
非常感谢您
PD:作为额外的加分点:我想获取Z轴上每个元素的平均值,并能够产生以下2D数组作为输出。 int x [2] [2] = {{4,5} {6,7}}
答案 0 :(得分:1)
您需要将for循环更改为此:
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
for (int k = 0; k < 3; ++k)
{
cout << "Element at x[" << k << "][" << i
<< "][" << j << "] = " << x[k][i][j]
<< endl;
}
}
}
变化最快的索引应该位于最内部,而变化少于其他的索引应该位于最外部。