【发布时间】: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