python - 使用 termcolor.colored 打印某些字符串不同的颜色?

标签 python colors

我想在Python中以不同的颜色打印某些字符串。我需要修改代码:

board_p1 = []
board_pc = []

board_size=6

for x in range(board_size):
    board_p1.append(["[W]"] * board_size)
    board_pc.append(["[W]"] * board_size)

def print_board(board):
    if board == board_p1:
        print colored("\n   Computers Board:    ",attrs=['underline'])
        for row in board:
            print " ".join(colored(element,"cyan") if element != "[X]" else colored(element,"red") if element != "[H]" else colored(element,"magenta") for element in row)
    if board == board_pc:
        print colored("\n    Players Board:     ",attrs=['underline'])
        for row in board_pc:
            print " ".join(colored(element,"cyan") if element != "[S]" else colored(element,"green") if element != "[X]" else colored(element,"red") if element != "[H]" else colored(element,"magenta") for element in row)

这样,当在列表中时,[H] 将打印为洋红色,[X] 将打印为红色,等等,我可以得到如下输出:

enter image description here

我遇到困难:

print " ".join(colored(element,"cyan") if element != "[S]" else colored(element,"green") if element != "[X]" else colored(element,"red") if element != "[H]" else colored(element,"magenta") for element in row)

以便以上述方式打印。

问:如何修改/编辑上面的代码行,以便在列表中看到 [X] 时将其打印为红色,[S] 打印为绿色,[H] ] 洋红色?

最佳答案

尽管由于添加了括号,以下内容可以正确解析:

print " ".join(colored(element,"cyan") if element != "[S]" else (colored(element,"green") if element != "[X]" else (colored(element,"red") if element != "[H]" else colored(element,"magenta"))) for element in row)

但是,由于否定条件,我无法判断它是否会产生您问题中的示例中描述和描述的映射。

但是根据该描述,我建议最好使用这样的字典:

element_colors = {'[W]': 'cyan', '[X]': 'red', '[S]': 'green', '[H]': 'magenta'}

print " ".join(colored(element, element_colors[element]) for element in row)

关于python - 使用 termcolor.colored 打印某些字符串不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582695/

相关文章:

python - 正则表达式捕获组的可选顺序

python - 以特殊条件连接 pandas 数据框

python - 使用 XlsxWriter 将 pandas 图表插入 Excel 文件

android - 黑色文本在 Android View 中显示为灰色

android - 如何在 Android 中更改 TextInputLayout 的 boxStrokeColor?

python - 尝试使用Scrapy从表中提取数据

java - 如何在Java中从IP获取子网

bash - grep'ing 后保留 ls 着色

c# - 在 c# 和 c dll 之间使用通用颜色值

mysql - 将 rgb 值迁移到 MYSQL 数据库中的 HSL 和十六进制