【问题标题】:Local scope for numpy set_printoptionsnumpy set_printoptions 的本地范围
【发布时间】:2016-06-27 09:43:52
【问题描述】:

np.set_printoptions 允许自定义 numpy 数组的漂亮打印。但是,对于不同的用例,我希望有不同的打印选项。

理想情况下,无需每次都重新定义整个选项。我正在考虑使用本地范围,例如:

with np.set_printoptions(precision=3):
    print my_numpy_array

但是,set_printoptions 似乎不支持 with 语句,因为会引发错误 (AttributeError: __exit__)。有没有办法在不创建自己漂亮的打印类的情况下完成这项工作?也就是说,我知道我可以创建自己的上下文管理器:

class PrettyPrint():
    def __init__(self, **options):
        self.options = options

    def __enter__(self):
        self.back = np.get_printoptions()
        np.set_printoptions(**self.options)

    def __exit__(self, *args):
        np.set_printoptions(**self.back)

并将其用作:

>>> print A
[ 0.29276529 -0.01866612  0.89768998]

>>> with PrettyPrint(precision=3):
        print A
[ 0.293 -0.019  0.898]

但是,有没有比创建新类更直接的方法(最好是内置的)?

【问题讨论】:

  • 有一种更简洁的方式来制作上下文管理器,shown here
  • @unutbu 不知道contextlib(也不是那个答案)谢谢!但它仍然意味着定义一个新函数。我想总比没有好。

标签: python arrays numpy pretty-print


【解决方案1】:

所以基于@unutbu给出的链接,而不是使用

with np.set_printoptions(precision=3):
    print (my_numpy_array)

我们应该使用:

with np.printoptions(precision=3):
    print my_numpy_array

这适用于我的情况。如果事情似乎没有改变,请尝试操作打印选项的其他参数,例如linewidth = 125, edgeitems = 7, threshold = 1000 等等。

【讨论】:

    【解决方案2】:

    试试

     np.array_repr(x, precision=6, suppress_small=True)
    

    或采用precision 等关键字的相关函数之一。看起来它可以控制许多(如果不是全部)打印选项。

    【讨论】:

    • 谢谢!它不完全等同于上下文管理器,但对我来说更具可读性(并且更短)。
    • np.core.arrayprint.py 是所有这些格式化操作的 Python 代码,包括 set_printoptions。它可能是在contexts 在 Python 中广泛使用之前编写的。
    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 2013-02-27
    • 1970-01-01
    相关资源
    最近更新 更多