[英]How to print a tabular dictionary in Python
假設我有以下形式的字典:
the_board = {(1,1) : ' ', (1,2) : ' ', (1,3) : ' ',
(2,1) : ' ', (2,2) : ' ', (2,3) : ' ',
(3,1) : ' ', (3,2) : ' ', (3,3) : ' ',}
我想逐行打印每一行。 目前,我正在執行以下操作:
def display(board):
var = list(board.values()) # Iterator to print out the table
i = 0
j = 0
maxi = len(var)
while i < maxi:
while j < (i + 3):
print(var[j], end="")
if j < i+2:
print('|', end='')
j += 1
print()
if i < (maxi-1):
print("-+-+-")
i += 3
我知道這很可能不是實現我想要的最“ Python方式”。 我將如何以更Python化的方式進行操作? (我知道我可以使用這些鍵來實現此目的,因為我給了它們坐標鍵,但是我可能需要在不使用有序/下標鍵的情況下打印表格字典,因此,我希望能找到更通用的解決方案)。
了解了Python的range函數,所以現在我的代碼如下:
def display(board):
var = list(board.values()) # Iterator to print out the table
maxi = len(var)
for i in range(0, maxi, 3):
for j in range(i, (i+3)):
print(var[j], end="")
if j < i+2:
print('|', end='')
print()
if i < (maxi-1):
print("-+-+-")
仍然不確定這是編寫它的最佳方法。
def chunks(l,n):
""" Split list into chunks of size n """
for i in range(0, len(l), n):
yield l[i:i+n]
def display(board):
for values in chunks(list(the_board.values()), 3):
print('|'.join(values)) # use str.join to concat strings with separators
print('-+-+-')
您可以設置列數:
the_board = {
(1, 1): ' ', (1, 2): ' ', (1, 3): ' ',
(2, 1): ' ', (2, 2): ' ', (2, 3): ' ',
(3, 1): ' ', (3, 2): ' ', (3, 3): ' '
}
def display(board, ncols):
items = list(board.values())
separate_line = '\n' + '+'.join('-' * ncols) + '\n'
item_lines = []
i = 0
while i + ncols <= len(items):
item_line = '|'.join(items[i:i + ncols])
item_lines.append(item_line)
i += ncols
output = separate_line.join(item_lines)
print(output)
display(the_board, ncols=3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.