如何在一行中打印numpy.array?

时间:2018-03-22 20:21:30

标签: python arrays python-3.x numpy line

我测试了PyCharm和IDLE,它们都将第7个数字打印到第二行。

输入:

import numpy as np
a=np.array([ 1.02090721,  1.02763091,  1.03899317,  1.00630297,  1.00127454, 0.89916715,  1.04486896])
print(a)

输出:

[ 1.02090721  1.02763091  1.03899317  1.00630297  1.00127454  0.89916715
  1.04486896]

如何在一行中打印它们?

3 个答案:

答案 0 :(得分:6)

np.set_printoptions允许修改"线宽"打印的NumPy数组:

>>> import numpy as np

>>> np.set_printoptions(linewidth=np.inf)
>>> a = np.array([ 1.02090721,  1.02763091,  1.03899317,  1.00630297,  1.00127454, 0.89916715,  1.04486896])
>>> print(a)
[1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896]

它将在一行中打印所有1D数组。使用多维数组,它不会轻易地工作。

here类似,如果你只是想暂时改变它,你可以使用一个上下文管理器:

import numpy as np
from contextlib import contextmanager

@contextmanager
def print_array_on_one_line():
    oldoptions = np.get_printoptions()
    np.set_printoptions(linewidth=np.inf)
    yield
    np.set_printoptions(**oldoptions)

然后你就这样使用它(假设新的解释器会话):

>>> import numpy as np
>>> np.random.random(10)  # default
[0.12854047 0.35702647 0.61189795 0.43945279 0.04606867 0.83215714
 0.4274313  0.6213961  0.29540808 0.13134124]

>>> with print_array_on_one_line():  # in this block it will be in one line
...     print(np.random.random(10))
[0.86671089 0.68990916 0.97760075 0.51284228 0.86199111 0.90252942 0.0689861  0.18049253 0.78477971 0.85592009]

>>> np.random.random(10)  # reset
[0.65625313 0.58415921 0.17207238 0.12483019 0.59113892 0.19527236
 0.20263972 0.30875768 0.50692189 0.02021453]

答案 1 :(得分:5)

如果您想要>>> print(a) [ 1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896] >>> str(a) '[1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715\n 1.04486896]' >>> np.array_str(a, max_line_width=np.inf) '[1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896]' >>> print(np.array_str(a, max_line_width=np.inf) [1.02090721 1.02763091 1.03899317 1.00630297 1.00127454 0.89916715 1.04486896] 的自定义版本,则答案为array_str

inf

如果您想更改每个数组的打印输出,请访问set_printoptions

答案 2 :(得分:0)

打印时键入强制转换为列表。

import numpy as np
a=np.array([ 1.02090721,  1.02763091,  1.03899317,  1.00630297,  1.00127454, 0.89916715,  1.04486896])
print(list(a))

这将在一行打印。