Python 输出带有按值着色的 float 的复杂行

标签 python printing colors floating-point format

这是我的第一个 python 程序,也是我第一次提出有关堆栈溢出的问题,所以如果我的代码一团糟或者我的问题格式不正确,我深表歉意。

我想打印我已经在打印的同一行,但每个 float 都应该根据其值使用不同的颜色。 (特别是 >.7 是绿色,.7< 是红色)最好的方法是什么?

oreName=[#string names]

#escape char? I know there has to be a better way than this
#but this is the best ive come up with as the escape char didnt
#work the way I thought it should for '%'
char = '%'

netProfitBroker=[
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]

##code that populates netProfitBroker

def printOutput(array):
  "this prints all of the lines"
  for i in range(0,10):
    print oreName[i]+"=   %.3f \t 5"%(array[0][i])+char+"=%.3f \t10"%(array[1][i])+char+"=%.3f"%(array[2][i])    


print "\nnet profit brokered"
printOutput(netProfitBroker)

输出看起来有点像这样:(当我在这里复制输出时,我丢失了一些/所有的空白格式)

net profit brokered

Veldspar   =   0.234     5%=0.340   10%=-0.017
Scordite   =   0.752     5%=0.297   10%=0.259
Pyroxeres  =   0.406     5%=1.612   10%=2.483
Plagioclase=   1.078     5%=0.103   10%=1.780
Omber      =   -7.120    5%=5.416   10%=4.612
Kernite    =   -10.822   5%=15.366  10%=6.626
Jaspet     =   17.772    5%=49.278  10%=62.380
Hemorphite =   -35.431   5%=82.912  10%=141.027
Gneiss     =   8.086     5%=-4638.549   10%=-3610.570
Arkonor    =   349.867   5%=-545.284    10%=-340.298

本质上:

"ore name=" arrayVal1 "5%="arrayVal2 "10%="arrayVal3

所有数组值都应打印到小数点后 3 位。

最佳答案

您可以在打印的开头使用 ASCII 颜色代码来更改颜色,例如 '\033[91m' 用于红色和 '\033[94m'

例如

if array[0][i] > 7:
   print '\033[94m' + oreName[i]+"=   %.3f \t 5"%(array[0][i])
elif array[0][i] < 7:
   print '\033[91m' + oreName[i]+"=   %.3f \t 5"%(array[0][i])

您可以阅读有关 ASCII 转义码的信息 here .

编辑:添加了额外的示例代码。

以下是您可以使用的一些常见颜色的列表:

Red = '\033[91m'
Green = '\033[92m'
Blue = '\033[94m'
Cyan = '\033[96m'
White = '\033[97m'
Yellow = '\033[93m'
Magenta = '\033[95m'
Grey = '\033[90m'
Black = '\033[90m'
Default = '\033[99m'

另外如评论中所述。您可以将它们链接起来以在同一行上获得不同的颜色。

print '\033[91m' + 'Red' + "\033[99m" + 'Normal' + '\033[94m' + 'Blue

你甚至可以做一个函数。

# Store a dictionary of colors.
COLOR = {
    'blue': '\033[94m',
    'default': '\033[99m',
    'grey': '\033[90m',
    'yellow': '\033[93m',
    'black': '\033[90m',
    'cyan': '\033[96m',
    'green': '\033[92m',
    'magenta': '\033[95m',
    'white': '\033[97m',
    'red': '\033[91m'
}


def print_with_color(message, color='red'):
    print(COLOR.get(color.lower(), COLOR['default']) + message)


print_with_color('hello colorful world!', 'magenta')
print_with_color('hello colorful world!', 'blue')

关于Python 输出带有按值着色的 float 的复杂行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15580303/

相关文章:

java - 打印机竞争状况?

jquery - 从第 n 个 child 中删除一个类(class)

css - 如何在鼠标悬停在图像 map 上时更改超链接的颜色属性?

python - Django 管理员自动保存

python - 我正在尝试使用 Python 3.x 从亚马逊抓取评论,但一无所获

python - 高效创建具有重复结构的 NumPy 数组

printing - SSRS - 按钮在 IE 中未对齐

python - AWS::RDS - 使用对流层的多可用区

c - 如何从RGB中检测绿色?

C# 确定图像中是否存在对象