Python 设置prettytable中列的列宽

Python 设置prettytable中列的列宽,python,prettytable,Python,Prettytable,我必须使用prettytable打印多个表,并且每个列的大小也应与其他表中相应列的大小相匹配。我没有找到任何可以指定每列宽度的函数。 列宽是根据最大字符串的长度确定的,每个表中的长度不同。 如何将每个表的列与其他列对齐您可以使用_max_width指定每列的宽度。 我有这张桌子: +-------+------+------------+ | index | type | name | +----- -+------+------------+ | 1 | 1 | us

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

您可以使用_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中未提及的任何字段,它与列中最长的字符串对齐