我希望输出数组在同一行

时间:2020-10-17 14:20:51

标签: python numpy

enter image description here

当我打印数组时,一行中只有四个元素在同一行上。我希望一行中的所有元素都打印在同一行上。该怎么办?

1 个答案:

答案 0 :(得分:1)

我认为这里的答案涵盖了您的问题:A more compact __repr__ for my numpy array?

您可以执行以下操作:

import numpy as np
from numpy.core.arrayprint import array_repr

a = np.array([[0.0 for x in range(9)] for y in range(3) ])
a[0,0] = 2.946e6
a[1,1] = 1.363e3
a[2,2] = 2.357e8
b = [a]

print(b)
#[array([[2.946e+06, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00,
#        0.000e+00, 0.000e+00, 0.000e+00],
#       [0.000e+00, 1.363e+03, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00,
#        0.000e+00, 0.000e+00, 0.000e+00],
#       [0.000e+00, 0.000e+00, 2.357e+08, 0.000e+00, 0.000e+00, 0.000e+00,
#        0.000e+00, 0.000e+00, 0.000e+00]])]

def __my_repr__(self):
    return array_repr(self).replace('\n', '').replace(' ', '').replace(',', ', ')
np.set_string_function(__my_repr__)
print(b)
#[array([[2.946e+06, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00], [0.000e+00, 1.363e+03, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00], [0.000e+00, 0.000e+00, 2.357e+08, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00]])]
相关问题