如何在Python中打印表格字典

时间:2018-09-04 02:01:51

标签: python dictionary

假设我有以下形式的字典:

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

仍然不确定这是编写它的最佳方法。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

嗨,如果我对您的理解正确,那应该是解决方法

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

答案 2 :(得分:0)

您可以设置列数:

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)
相关问题