我可以简化井字游戏的棋盘吗?蟒蛇

问题描述 投票:0回答:1

我制作了一个带有列表和印刷品的板,它看起来像这样:

+-----------------+
|  1  |  2  |  3  |
+-----------------+
|  4  |  5  |  6  |
+-----------------+
|  7  |  8  |  9  |
+-----------------+

我可以将所有这些分配给一件事(变量/列表/元组/字典)并打印它吗?

这是我的代码:

    board_list = [[1,2,3], [4,5,6], [7,8,9]]
    print("+-----------------+")
    print("| ", board_list[0][0], " | ", board_list[0][1], " | ", board_list[0][2], " |")
    print("+-----------------+")
    print("| ", board_list[1][0], " | ", board_list[1][1], " | ", board_list[1][2], " |")
    print("+-----------------+")
    print("| ", board_list[2][0], " | ", board_list[2][1], " | ", board_list[2][2], " |")
    print("+-----------------+")

但是有办法做到这一点吗?

    board_representation = "+------------------------------+
    | board_list[0][0], | board_list[0][1], | board_list[0][2]
    +------------------------------+
    | board_list[1][0], | board_list[1][1], | board_list[1][2]
    +------------------------------+
    | board_list[2],[0], | board_list[2][1], | board_list[2][2]
    +------------------------------+"
   print(board_representation) 

第一个代码的输出:

+-----------------+
|  1  |  2  |  3  |
+-----------------+
|  4  |  5  |  6  |
+-----------------+
|  7  |  8  |  9  |
+-----------------+
python tic-tac-toe
1个回答
0
投票

您可以使用 f 字符串和三引号来表示带有插入值的多行字符串:

board_list = [[1,2,3], [4,5,6], [7,8,9]]
board_representation = f'''\
+-----------+
| {board_list[0][0]} | {board_list[0][1]} | {board_list[0][2]} |
+-----------+
| {board_list[1][0]} | {board_list[1][1]} | {board_list[1][2]} |
+-----------+
| {board_list[2][0]} | {board_list[2][1]} | {board_list[2][2]} |
+-----------+
'''
print(board_representation)

输出:

+-----------+
| 1 | 2 | 3 |
+-----------+
| 4 | 5 | 6 |
+-----------+
| 7 | 8 | 9 |
+-----------+
© www.soinside.com 2019 - 2024. All rights reserved.