如何在 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

我知道这很可能不是实现我想要的最“pythonic 方式”。我将如何以更 Pythonic 的方式做到这一点?(我知道我可以使用键来实现这一点,因为我给了它们坐标键,但我可能需要打印一个没有有序/下标键的表格字典,所以我希望有一个更通用的解决方案)。

 

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

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


慕标5832272
浏览 371回答 3
3回答

红糖糍粑

def chunks(l,n):""" Split list into chunks of size n """&nbsp; &nbsp; for i in range(0, len(l), n):&nbsp; &nbsp; &nbsp; &nbsp; yield l[i:i+n]def display(board):&nbsp; &nbsp; for values in chunks(list(the_board.values()), 3):&nbsp; &nbsp; &nbsp; &nbsp; print('|'.join(values))&nbsp; &nbsp; # use str.join to concat strings with separators&nbsp; &nbsp; &nbsp; &nbsp; print('-+-+-')

慕盖茨4494581

嗨,如果我理解正确的话,这应该是解决方案board = {(1,1) : ' a ', (1,2) : ' b ', (1,3) : ' c&nbsp; ',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(2,1) : 'd ', (2,2) : 'e ', (2,3) : ' f ',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(3,1) : 'g ', (3,2) : ' h', (3,3) : ' i',}&nbsp; print ( "Cordiantes --- Values")&nbsp; for key , value in board.items():&nbsp; print(key , "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;" , value)输出将是

慕桂英546537

您可以设置列数:the_board = {&nbsp; &nbsp; (1, 1): ' ', (1, 2): ' ', (1, 3): ' ',&nbsp; &nbsp; (2, 1): ' ', (2, 2): ' ', (2, 3): ' ',&nbsp; &nbsp; (3, 1): ' ', (3, 2): ' ', (3, 3): ' '}def display(board, ncols):&nbsp; &nbsp; items = list(board.values())&nbsp; &nbsp; separate_line = '\n' + '+'.join('-' * ncols) + '\n'&nbsp; &nbsp; item_lines = []&nbsp; &nbsp; i = 0&nbsp; &nbsp; while i + ncols <= len(items):&nbsp; &nbsp; &nbsp; &nbsp; item_line = '|'.join(items[i:i + ncols])&nbsp; &nbsp; &nbsp; &nbsp; item_lines.append(item_line)&nbsp; &nbsp; &nbsp; &nbsp; i += ncols&nbsp; &nbsp; output = separate_line.join(item_lines)&nbsp; &nbsp; print(output)display(the_board, ncols=3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python