【问题标题】:Coloring entries in an Matrix/2D-numpy array?矩阵/二维numpy数组中的着色条目?
【发布时间】:2019-06-07 14:56:35
【问题描述】:

我正在学习 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,并根据条件将该值与某种背景颜色附加到新矩阵中,但我认为有一种更优雅的方法可以做到这一点......

【问题讨论】:

  • 您可以绘制数组的热图
  • 不要使用nditer。它不会使通过数组的迭代变得更容易或更快。

标签: arrays python-3.x numpy matrix colors


【解决方案1】:

以下将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]))
>>> 

要添加背景颜色,请使用fn

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

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的建议修改了打印功能

【讨论】:

  • 您的print 函数如果分成两行可能会更清晰。一种用于定义格式字符串:fmt = "\n".join([row_sep.join(["{}"]*m)]*n),另一种用于将其应用于数组输入:print(fmt.format(*map.ravel()))
  • 哦,太好了!我没有意识到如果不遍历整个事情就可以做到这一点。!编辑:神经,我忽略了for循环。仍然:这比我做的效率更高。非常感谢!
  • @MaxPower8993 尽管打印使用循环,但存储的 bg 值的 mat 创建实际上是矢量化的
  • @vmandke 感谢您分享这个有效的解决方案。我只想补充一点,对于某些 Windows 用户,颜色可能最终不会显示。 The answer by Glenn Slayden (the highest voted one as of this writing) 是我遵循的(作为 Windows 10 用户),以使其正常工作。
  • @MoAboulmagd 谢谢!!!这很有趣,我还没有真正在 Windows 上工作过,所以只是假设 Python 将处理较低的抽象,并引发适当的错误......
猜你喜欢
  • 2016-09-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 2020-08-28
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多