【问题标题】:Setting column width for columns in prettytable为漂亮表中的列设置列宽
【发布时间】:2020-06-11 10:41:10
【问题描述】:

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

【问题讨论】:

    标签: python prettytable


    【解决方案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 中未提及的任何字段,都与该列中最长的字符串对齐。

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 2011-11-05
      • 2019-08-13
      • 2012-10-24
      • 2018-12-01
      • 1970-01-01
      • 2017-05-18
      • 2011-01-02
      • 2022-01-22
      相关资源
      最近更新 更多