gpt4 book ai didi

python - numpy set_printoptions 的本地范围

转载 作者:太空狗 更新时间:2023-10-30 02:57:09 26 4
gpt4 key购买 nike

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

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

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

但是,set_printoptions 似乎不支持 with 语句,因为会抛出错误 (AttributeError: __exit__)。有什么方法可以在不创建自己的 pretty-print 类的情况下完成这项工作吗?也就是说,我知道我可以创建自己的上下文管理器:

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]

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

最佳答案

所以根据@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 等等。

关于python - numpy set_printoptions 的本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38050643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com