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

Printing certain strings different colour with termcolor.colored?

我想用python打印一些不同颜色的弦。我需要修改代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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("
   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("
    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

我在以下方面遇到困难:

1
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]打印为洋红?


尽管我国正确下面两parentheses added to the:P></

1
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)

不管一个人多,两negated to the条件,正可以告诉如果它会产生映射和描述的程序办理depicted the the example中在你的问题。P></

但要从蓝晶石,description会更好,它会是这样:在词典的使用P></

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

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