【问题标题】:Printing certain strings different colour with termcolor.colored?用termcolor.colored打印某些不同颜色的字符串?
【发布时间】:2016-06-02 04:30:07
【问题描述】:

我想在 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] 将显示为红色,等等我可以得到如下输出:

我有困难:

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] ] 洋红色?

【问题讨论】:

    标签: python colors


    【解决方案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)
    

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

    但是从那个描述来看,我建议最好使用这样的字典:

    element_colors = {'[W]': 'cyan', '[X]': 'red', '[S]': 'green', '[H]': 'magenta'}
    
    print " ".join(colored(element, element_colors[element]) for element in row)
    

    【讨论】:

    • 完美,非常感谢!我更喜欢你对字典的建议,因为它是一种更简单、更有效的方式!
    猜你喜欢
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2015-05-23
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    相关资源
    最近更新 更多