[英]Print 2d list as a game board
我有一個二維列表 [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] 我想打印它out 以匹配以下格式。
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
它不應該是硬編碼的並且列表的長度 = n 所以這個列表 n=4 但如果列表 n=5 每行會有 5 個數字,兩邊的數字會是 0,1,2,3,4 .
到目前為止,我所擁有的是:
for row in board:
for column in row:
print(column, end="")
print("")
僅將列表輸出為:
1234
4331
3211
2221
請幫我添加所有特殊的東西。
可能是一個不受歡迎的意見,但我認為這些問題真的很有趣。
即使您更改行數,甚至每行中的項目數,此解決方案也會正確格式化內容。
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
編輯以刪除我自己的測試並反映給定的問題。
所以我找到了你想做的事情的解決方案,但是我認為它可以改進很多(不是在 python 中編程很多),但無論如何我都會把它留在這里:)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
好吧,對於第一行,您幾乎打印了 2 個空格,然后是 0 和板中列數之間的所有數字。 您可以為此使用“范圍”功能。 然后您必須打印正確數量的“X”。 正確的數量是列數 + 4,我想你能明白為什么。
你應該保持一個從 0 開始的計數器。對於你打印的每一行,你必須打印計數器的字符串值,然后是一個星號 (*),然后是你的行,然后是一個星號 (*),最后是相同的計數器值。 您必須為每一行將計數器加一。
最后 2 行與前 2 行相同。
我不想分享我的代碼,因為這是一個如此簡單的問題,我認為從長遠來看,您自己解決它會對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.