1

我必须使用打印多个表prettytable,并且每列的大小也应与其他表中相应列的大小相匹配。我没有找到任何可以指定每列宽度的函数。列是根据最大字符串的长度确定的,每个表的长度不同。如何将每个表的列与其他列对齐

4

1 回答 1

1

您可以使用 _max_width 指定每列的宽度。我有这张桌子:

+-------+------+------------+
| index | type |    name    |
+----- -+------+------------+
|   1   |  1   | username_1 |
|   2   |  2   | username_2 |
+------ +------+------------+

在为两列指定宽度后,我得到下面的输出

def print_dict_to_table(mydict):
    t = PrettyTable(mydict[0].__dict__.keys())
    t._max_width = {"name":3, "type":3}
    for i in range(0, len(mydict)):
        t.add_row(mydict[i].__dict__.values())
    print(t)


+-------+------+------+
| index | type | name |
+-------+------+------+
|   1   |  1   | user |
|       |      | name |
|       |      |  _1  |
|   2   |  2   | user |
|       |      | name |
|       |      |  _2  |
+-------+------+------+

您可以为列宽创建字典并在表中重用它。对于 _max_widths 中未提及的任何字段,它与列中最长的字符串对齐。

于 2020-07-14T05:09:48.647 回答