如何用Python打印表格词典

2024-04-25 01:21:19 发布

您现在位置: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的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("-+-+-")

还是不确定这是最好的写法。你知道吗


Tags: thetoboardifvardefdisplayrange
3条回答

嗨,如果我没听错的话,这应该是解决办法

board = {(1,1) : ' a ', (1,2) : ' b ', (1,3) : ' c  ',
             (2,1) : 'd ', (2,2) : 'e ', (2,3) : ' f ',
             (3,1) : 'g ', (3,2) : ' h', (3,3) : ' i',}

  print ( "Cordiantes  - Values")
  for key , value in board.items():
  print(key , "         " , value)

输出将是

enter image description here

您可以设置列数:

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)
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('-+-+-')

相关问题 更多 >