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

2024-04-07

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

Input:

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

Output:

[ 1.02090721  1.02763091  1.03899317  1.00630297  1.00127454  0.89916715
  1.04486896]

如何将它们打印在一行中?


np.set_printoptions https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html它允许修改打印的 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]

它将在一行中打印所有一维数组。对于多维数组来说,它不会那么容易地工作。


如同here https://stackoverflow.com/a/45831462/5393381如果您只想使用上下文管理器暂时地改变一下:

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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在一行中打印 numpy.array? 的相关文章

随机推荐