我正在尝试最终打印'board',但控制台不会超出这部分代码:
board1=(" ")
board2=(" ")
board3=(" ")
board4=(" ")
board5=(" ")
board6=(" ")
board7=(" ")
board8=(" ")
board9=(" ")
board= ((board1+" | "+board2+" | "+board3)
["---------"]
(board4+" | "+board5+" | "+board6)
["---------"]
(board7+" | "+board8+" | "+board9))
它只返回此错误代码。有人有什么想法吗?
Traceback (most recent call last):
File "C:\Users\Jaymeson\Desktop\Rock Paper Scissors CPU.py", line 36, in <module>
["---------"]
TypeError: string indices must be integers
>>>
我希望输出为:
| |
---------
| |
---------
| |
答案 0 :(得分:2)
(board1+" | "+board2+" | "+board3)
创建一个字符串。然后,您要求Python使用string[...]
索引该字符串。字符串只能采用整数(单个字符的位置)。你改为给它字符串"---------"
。
如果您想在单元格之间绘制线条,请不要在这些线条周围使用[...]
。只是连接(并包含换行符):
board= ((board1+" | "+board2+" | "+board3) +
"\n---------\n" +
(board4+" | "+board5+" | "+board6) +
"\n---------\n" +
(board7+" | "+board8+" | "+board9))
我改用嵌套列表,然后再打印:
board = [[' ' for _ in range(3)] for _ in range(3)]
def print_board(board):
print(*(' | '.join(row) for row in board),
sep='\n--+---+--\n')
现在,嵌套列表中有一个3 x 3矩阵,可以根据需要更改单元格:
>>> def print_board(board):
... print(*(' | '.join(row) for row in board),
... sep='\n--+---+--\n')
...
>>> board = [[' ' for _ in range(3)] for _ in range(3)]
>>> print_board(board)
| |
--+---+--
| |
--+---+--
| |
>>> board[0][0] = 'O'
>>> board[1][1] = 'X'
>>> print_board(board)
O | |
--+---+--
| X |
--+---+--
| |