簡體   English   中英

如何將字典格式化為 5x5 網格?

[英]How do you format a dictionary into a 5x5 grid?

我正在嘗試將我的字典打印成 5x5 網格,但不知道該怎么做。

game_dict = {(0,0): 0, (0,1): 0, (0,2): 0, (0,3): 0, (0,4): 0, 
             (1,0): 0, (1,1): 0, (1,2): 0, (1,3): 0, (1,4): 0,
             (2,0): 0, (2,1): 0, (2,2): 0, (2,3): 0, (2,4): 0,
             (3,0): 0, (3,1): 0, (3,2): 0, (3,3): 0, (3,4): 0,
             (4,0): 0, (4,1): 0, (4,2): 0, (4,3): 0, (4,4): 0}

print(*game_dict.values())

這打印出 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

我想打印

0 0 0 0 0
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

當前位置 = (0, 0)

game_dict[str(current_position)] =“X”

X 0 0 0 0
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0

通過遍歷坐標,您可以很容易地做您想做的事:

width = 5
height = 5
for y in range(height):
    row = [game_dict[(x, y)] for x in range(width)]
    print(*row)

但是,如果您的坐標始終是整數,則只需使用列表列表就可以使這更加簡單。

暫無
暫無

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

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