gpt4 book ai didi

python - 我可以将 numpy 数组的值打印为绿色(如果为正)或红色(如果为负)吗?

转载 作者:行者123 更新时间:2023-11-30 22:21:53 25 4
gpt4 key购买 nike

在将 float 的 numpy 数组打印到控制台时,我想要一个快速的视觉提示。如何使用颜色来表示积极/消极?

我发现了这种改变控制台颜色的奇怪方法,但我不确定它对我的情况是否有帮助:

>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello'+ENDCOLOR)
hello # <-- this is yellow
>>>this is in your regular console color

但是如果你省略最后一个字符串:

>>>YELLOW = '\033[93m'
>>>ENDCOLOR = '\033[0m'
>>>print(YELLOW+'hello')
hello #<-- it's yellow
>>>this is yellow as well, until you print ENDCOLOR

最佳答案

最简洁的方法是按照 Vikas Damodar 的建议,在 np.set_printoptions 和 colorama 中使用格式化程序 kwarg:

import colorama
import numpy as np

def color_sign(x):
c = colorama.Fore.GREEN if x > 0 else colorama.Fore.RED
return f'{c}{x}'

np.set_printoptions(formatter={'float': color_sign})

请注意,这是一个全局配置,并将按照此约定打印所有数组。

关于python - 我可以将 numpy 数组的值打印为绿色(如果为正)或红色(如果为负)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48498824/

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