I have a numpy three-dimensional complex array defined as follows:
> import numpy as np > a = np.random.rand(2,3,4) + np.random.rand(2,3,4) * 1j > a array([[[ 0.40506245+0.68587874j, 0.74700976+0.73208816j, 0.42010818+0.31124884j, 0.27181199+0.54599156j], [ 0.29457621+0.34057513j, 0.82490182+0.63943948j, 0.46887722+0.12734375j, 0.77184637+0.21522095j], [ 0.67774944+0.8208908j , 0.41476702+0.85332392j, 0.10084665+0.56146324j, 0.71325041+0.77306548j]], [[ 0.77843387+0.23660274j, 0.23671262+0.63997834j, 0.60831419+0.41741288j, 0.53870756+0.13747055j], [ 0.12477767+0.54603678j, 0.60537090+0.89208227j, 0.16027151+0.17575777j, 0.18801875+0.27282324j], [ 0.82308271+0.97238411j, 0.47458327+0.75200695j, 0.16085009+0.60620705j, 0.79766571+0.76470634j]]])
I need to print it in line s in a specific format that is a bit like MATLAB, and the best way I found is this: (I am best to describe the format with this code)
> s = '' > for k in range(a.shape[2]): > for j in range(a.shape[1]): > for i in range(a.shape[0]): > s += str(a[i,j,k].real) + ' ' > for j in range(a.shape[1]): > for i in range(a.shape[0]): > s += str(a[i,j,k].imag) + ' '
I am not satisfied with this code, which does not look very "pythonic" to me (I come from C ++ and know little about Python). I'm sure Python provides a good syntax that can be used here (like list comprehension), but I'm not very familiar with it.
So my question is this: how can I improve this code to be more pythonic?
Edit: this 3D array is considered as an array of 2 by 3 complex matrices. The format consists of printing the real part of the first matrix, then its imaginary part and repeating it for each matrix.
This is the format you get when you run this code in MATLAB:
> a = rand(2,3,4) + rand(2,3,4) * 1i; > s = sprintf('%g %g ', [real(a) imag(a)]);
My main goal is compatibility with this format.