Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果是正数,我可以用绿色打印numpy数组的值吗?如果是负数,我可以用红色打印吗?_Python_Numpy_Colors - Fatal编程技术网

Python 如果是正数,我可以用绿色打印numpy数组的值吗?如果是负数,我可以用红色打印吗?

Python 如果是正数,我可以用绿色打印numpy数组的值吗?如果是负数,我可以用红色打印吗?,python,numpy,colors,Python,Numpy,Colors,我想要一个快速的视觉提示,当打印一个浮点数数组到控制台。我如何使用颜色来表示积极性/消极性 我发现了这种改变控制台颜色的方法,但我不确定它对我的情况是否有帮助: >>>YELLOW = '\033[93m' >>>ENDCOLOR = '\033[0m' >>>print(YELLOW+'hello'+ENDCOLOR) hello # <-- this is yellow >>>this is in your reg

我想要一个快速的视觉提示,当打印一个浮点数数组到控制台。我如何使用颜色来表示积极性/消极性

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

>>>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
我认为这是一个很好的方法:

from colorama import fore

print(f'{fore.Green}green color')

最干净的方法是按照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})

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

我认为您需要编写一个自定义函数,将数组元素与所需的ANSI代码一起打印。它可以工作!我只是在程序末尾添加了打印“\033[0m”来恢复默认的控制台颜色。你可以简单地使用colorama.Fore.RESET,它也可以在其他平台上工作。是的,看起来更好