gpt4 book ai didi

arrays - Matrix/2D-numpy 数组中的着色条目?

转载 作者:行者123 更新时间:2023-12-03 23:51:47 25 4
gpt4 key购买 nike

我正在学习 python3,我想打印一个颜色编码(CLI)的矩阵/二维数组。因此,假设我想为这些整数中的每一个分配特定的背景颜色,从而创建马赛克风格的外观。

我已经想出了如何用随机整数填充给定大小的矩阵,但我无法理解如何从这里开始为矩阵中的每个条目实现背景着色,具体取决于其值.这是我走了多远:

from random import randint
import numpy as np

def generate():
n = 10
m = 0
map = np.random.randint(4 + 1, size=(n, n))
print(map)

for element in np.nditer(map):
# iterating over each column is probably not the way to go...


generate()

有没有办法做到这一点?我正在考虑遍历矩阵的每一列并通过几个 if 条件检查条目是 0、1、2、3 还是 4,然后根据条件将该值与特定的背景颜色附加到新矩阵中,但我认为有一种更优雅的方式来做到这一点......

最佳答案

以下将print控制台上的彩色输出...

>>> map = np.random.randint(4 + 1, size=(10, 10))
>>> def get_color_coded_str(i):
... return "\033[3{}m{}\033[0m".format(i+1, i)
...
>>> map_modified = np.vectorize(get_color_coded_str)(map)
>>> print("\n".join([" ".join(["{}"]*10)]*10).format(*[x for y in map_modified.tolist() for x in y]))
>>>

enter image description here

要添加背景颜色,请使用以下 fn
>>> def get_color_coded_str(i):
... return "\033[4{}m{}\033[0m".format(i+1, i)

enter image description here
from random import randint
import numpy as np

def get_color_coded_str(i):
return "\033[3{}m{}\033[0m".format(i+1, i)

def get_color_coded_background(i):
return "\033[4{}m {} \033[0m".format(i+1, i)

def print_a_ndarray(map, row_sep=" "):
n, m = map.shape
fmt_str = "\n".join([row_sep.join(["{}"]*m)]*n)
print(fmt_str.format(*map.ravel()))

n = 10
m = 20
map = np.random.randint(4 + 1, size=(n, m))
map_modified = np.vectorize(get_color_coded_str)(map)
print_a_ndarray(map_modified)
back_map_modified = np.vectorize(get_color_coded_background)(map)
print("-------------------------------------------------------")
print_a_ndarray(back_map_modified, row_sep="")

PS:按照@hpaulj 的建议修改了打印功能

关于arrays - Matrix/2D-numpy 数组中的着色条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56496731/

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