我如何将东西放在 table 中 python

How do I put things in a table in python

如何在 python 中制作 table。我在学校做这件事,那里不允许我使用任何额外的插件,例如 tabulate 或 texttable 和漂亮的 table 所以你能指导我如何做吗谢谢它是为了 python 3.4 或 python 3.5

我应该把它作为评论,但由于我没有足够的声誉,所以我将它作为答案发布。检查 this

def print_table(table):
    col_width = [max(len(x) for x in col) for col in zip(*table)]
    for line in table:
        print ("| " + " | ".join("{:{}}".format(x, col_width[i])
                                for i, x in enumerate(line)) + " |")

这是基于@SOReadytoHelp 的解决方案。我将其更新为 Python 3 并包含了一个示例。

def print_table(table):
    col_width = [max(len(str(x)) for x in col) for col in zip(*table)]
    for line in table:
        print("| " + " | ".join("{:{}}".format(x, col_width[i])
                                for i, x in enumerate(line)) + " |")


table = [['/', 2,    3],
         ['a', '2a', '3a'],
         ['b', '2b', '3b']]

print_table(table)

打印

| / |  2 |  3 |
| a | 2a | 3a |
| b | 2b | 3b |