簡體   English   中英

如何使用for循環在python中打印

[英]How to print proprely in python using for loops

我想知道我是否只是想以錯誤的方式做某事或者我是否接近可行的解決方案。

我必須從老師給出的字典中打印一個棋盤。

到目前為止這是我的代碼:

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個不同的列表並以這種方式打印出來?

謝謝!

編輯:

輸出: 產量

strunicode對象上使用方法ljustrjust來確保字符串始終以您選擇的填充字符以恆定長度打印。 在你的情況下:

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) 0,8 range(0, 8)而不是range(0, 7)因為它是一個非包容范圍; 另外, range(0, N)僅等於range(N)

注意2:如果你需要使用除' '之外的字符串填充,你可以將可選的第二個參數傳遞給ljust (和rjust )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM