我有一个名为board的列表,如下所示:
board = [[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]]
我编写了一个功能,可以将该板输出到控制台,就像数独板一样:
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - + - - - + - - -")
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
print("| ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")
print_board(board)
>>>
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
- - - + - - - + - - -
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
- - - + - - - + - - -
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
现在,我不想将此板输出到控制台,而是将可变板重新分配为“已转换”板的字符串。我该怎么办?
答案 0 :(得分:0)
只需考虑打印的行为,然后分配一个空字符串,并继续将打印的内容连接到该字符串。
因此,对于普通的print
,在字符串末尾添加换行符,对于print with end=""
参数,我们将不添加任何内容,还将整数也转换为字符串
def print_board(bo):
s = ''
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
s += "- - - + - - - + - - -\n"
for j in range(len(bo[0])):
if j % 3 == 0 and j != 0:
s += "| "
if j == 8:
s += str(bo[i][j])+'\n'
else:
s += str(bo[i][j]) + " "
return s
那么您的输出将是
board = [[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]]
print(print_board(board))
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
- - - + - - - + - - -
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
- - - + - - - + - - -
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0
0 0 0 | 0 0 0 | 0 0 0