如何使用for循环在python中正确打印

时间:2013-10-22 21:11:06

标签: python printing dictionary

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

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

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

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个不同的列表并以这种方式打印出来?

谢谢!

编辑:

输出:Output

1 个答案:

答案 0 :(得分:2)

使用ljustrjust对象上的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(和rjust)。