如何在python中将2d数组打印为带有短划线和+符号的网格



我目前正在开发一款connect 4游戏,我需要2d数组,但问题是我想以短划线(-(和(+(符号打印2d数组。此外,我还需要在每行和每列旁边打印行和列号。此外,当用户进入他的轮次时,它应该显示在适当的单元格中。这是我的代码,它不能正常工作

board=[['','','','','',''],['','','','','',''],['','','','','',''],
['','','','','',''],['','','','','',''],['','','','','','']]
i=0
j=0
for r in board:
print(i,end="|")
for c in r:
print('+',end="---")
print(c,end="")
print('+')
i=i+1

输出如下:

0|+---+---+---+---+---+---+
1|+---+---+---+---+---+---+
2|+---+---+---+---+---+---+
3|+---+---+---+---+---+---+
4|+---+---+---+---+---+---+
5|+---+---+---+---+---+---+

但是我想要像这个一样的东西

0   1   2    3   4  5
+---+---+---+---+---+---+
0| x |   |   |   |   |   | 
+---+---+---+---+---+---+
1|   |   |   |   |   |   |
+---+---+---+---+---+---+
2|   |   |   |   |   |   |
+---+---+---+---+---+---+
3|   |   |   |   |   |   |
+---+---+---+---+---+---+
4|   |   |   |   |   |   |

其中x是我需要存储在2d阵列中并在适当位置打印的符号。任何解决方案

对于这个任务的主要部分,有一个很好的代码高尔夫答案,但我想这可能有点令人困惑。

因此,通过采纳其中的一些想法,并将其与您的代码相结合,我提出了

board = [['', '', '', '', '', ''], ['', '', '', '', '', ''],
['', '', '', '', '', ''],
['', '', '', '', '', ''], ['', '', '', '', '', ''],
['', '', '', '', '', '']]
x_loc = (2,5)
x_symbol = "X"
# print column numbers on top
columns = len(board[0])
print('   ', '   '.join([str(val) for val in range(columns)]))
row_separator = f'  +{"---+" * columns}'
for i_row, r in enumerate(board):
print(row_separator)
# print row number
print(i_row, end="")
# depending on location of X, either print a row including X or an empty row
if i_row == x_loc[0]:
print(f' |{"   |" * (x_loc[1])} {x_symbol} |{"   |" * (columns-x_loc[1]-1)}')
else:
print(f' |{"   |" * columns}')
# print closing row separator
print(row_separator)

结果是:

0   1   2   3   4   5
+---+---+---+---+---+---+
0 |   |   |   |   |   |   |
+---+---+---+---+---+---+
1 |   |   |   |   |   |   |
+---+---+---+---+---+---+
2 |   |   |   |   |   | X |
+---+---+---+---+---+---+
3 |   |   |   |   |   |   |
+---+---+---+---+---+---+
4 |   |   |   |   |   |   |
+---+---+---+---+---+---+
5 |   |   |   |   |   |   |
+---+---+---+---+---+---+

最新更新