如何在一行中打印一个numpy.array? [英] How to print a numpy.array in one line?

查看:111
本文介绍了如何在一行中打印一个numpy.array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tested PyCharm and IDLE, both of them print the 7th number to a second line.

输入:

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]

如何将它们打印成一行?

How can I print them in one line?

推荐答案

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

There is np.set_printoptions which allows to modify the "line-width" of the printed NumPy array:

>>> 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]

它将在一行中打印所有一维数组.对于多维数组,它将无法轻松地工作.

It will print all 1D arrays in one line. It won't work that easily with multidimensional arrays.

类似于在此,如果您只是想临时更改该内容,则可以使用contextmanager:

Similar to here you could use a contextmanager if you just want to temporarily change that:

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)

然后按如下所示使用它(假定使用了新的解释程序会话):

Then you use it like this (fresh interpreter session assumed):

>>> 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]

这篇关于如何在一行中打印一个numpy.array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆