假设我在 Python 的 numpy 数组中有一个矩阵
In [3]: my_matrix
Out[3]:
array([[ 2., 2., 2., 2., 2., 2., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 2., 2., 2., 2., 0., 0., 0.,
0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 2., 2.,
2., 2., 2., 2., 2.]])
有没有办法让 Python/IPython 将我的数组打印为:
[ 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2;
0 0 0 0 0 0 2 2 2 2 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 2 2 ]
? (~类似于MATLAB的做法)
此外,我注意到 IPython 在打印 numpy
数组时不会使用我的终端的整个宽度。其他功能可以(例如 pprint.pprint
)。我该如何改变它?
最佳答案
使用numpy.set_printoptions .增加线宽:
np.set_printoptions(linewidth=150)
将 150 替换为您需要的任何内容。现在,按照您的要求打印(我猜这意味着没有小数点):
print my_matrix.astype('i')
如果您有浮点值,您还可以使用选项 precision
控制打印输出的精度:
np.set_printoptions(precision=3)
关于python - 在 Python 中类似矩阵的二维数组打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676256/