0

我想知道我是否只是想以错误的方式做某事,或者我是否接近可行的解决方案。

我必须从老师给的字典中打印一个棋盘。

到目前为止,这是我的代码:

def printBoard(board):
x = 0
for x in range(0,7):
    print("|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|")
    print("|             |             |             |             |             |             |             |             |")
    print("|",board[0,x],"|",board[1,x],"|",board[2,x],"|",board[3,x],"|",board[4,x],"|",board[5,x],"|",board[6,x],board[7,x])
    print("|             |             |             |             |             |             |             |             |")

print("|-------------|-------------|-------------|-------------|-------------|-------------|-------------|-------------|")

board =   {
                (0,0):"Rook[B]",(1,0):"Knight[B]",(2,0):"Bishop[B]", (3,0):"Queen[B]",   (4,0):"King[B]", (5,0):"Bishop[B]", (6,0):"Knight[B]",(7,0):"Rook[B]",
                (0,1):"Pawn[B]",(1,1):"Pawn[B]",    (2,1):"Pawn[B]",(3,1):"Pawn[B]",    (4,1):"Pawn[B]",(5,1):"Pawn[B]",(6,1):"Pawn[B]",    (7,1):"Pawn[B]",
                (0,2):"EMPTY",   (1,2):"EMPTY",       (2,2):"EMPTY",   (3,2):"EMPTY",       (4,2):"EMPTY",   (5,2):"EMPTY",   (6,2):"EMPTY",       (7,2):"EMPTY",
                (0,3):"EMPTY",   (1,3):"EMPTY",       (2,3):"EMPTY",   (3,3):"EMPTY",       (4,3):"EMPTY",   (5,3):"EMPTY",   (6,3):"EMPTY",       (7,3):"EMPTY",
                (0,4):"EMPTY",   (1,4):"EMPTY",       (2,4):"EMPTY",   (3,4):"EMPTY",       (4,4):"EMPTY",   (5,4):"EMPTY",   (6,4):"EMPTY",       (7,4):"EMPTY",
                (0,5):"EMPTY",   (1,5):"EMPTY",       (2,5):"EMPTY",   (3,5):"EMPTY",       (4,5):"EMPTY",   (5,5):"EMPTY",   (6,5):"EMPTY",       (7,5):"EMPTY",
                (0,6):"Pawn[N]",(1,6):"Pawn[N]",    (2,6):"Pawn[N]",(3,6):"Pawn[N]",    (4,6):"Pawn[N]",(5,6):"Pawn[N]",(6,6):"Pawn[N]",    (7,6):"Pawn[N]",
                (0,7):"Rook[N]",(1,7):"Knight[N]",(2,7):"Bishop[N]", (3,7):"Queen[N]",   (4,7):"King[N]", (5,7):"Bishop[N]", (6,7):"Knight[N]",(7,7):"Rook[N]",
                }

printBoard(board)

我的问题是我无法对齐列。

也许我应该将字典发送到 8 个不同的列表中并以这种方式打印?

谢谢!

编辑 :

输出 :输出

4

1 回答 1

2

使用方法ljust和对象rjust来确保字符串始终以恒定长度打印,并带有您选择的填充字符strunicode在你的情况下:

board[0, x].ljust(11)

评估为例如

'Pawn[B]      '

所以一行会被打印出来

print("|", board[0, x].ljust(11), "|", board[1, x].ljust(11, ' '), ...)

但更紧凑的版本是:

for x in range(8):
    row = [board[y, x] for y in range(8)]
    print('|%s|' % '|'.join(cell.lpad(13) for cell in row)

注意1:range不需要range(0, 8)因为它是range(0, 7)一个非包含范围;也,range(0, N)等价于range(N)

注意2:如果您需要使用 以外的字符串进行填充' ',可以将可选的第二个参数传递给ljust(and rjust)。

于 2013-10-22T21:13:59.673 回答