Python table 有多个 header 行

Python table with multiple header lines

我需要创建一个 table 来显示在不同条件下收集的多组数据。这就是我需要 table 的样子:

        Config 1        Config 2
Test    Data 1  Data 2  Data 1  Data 2
abc     123     123     123     123

所以系统设置了配置 1,然后收集了两组数据。使用配置 2 重置系统,然后收集相同的数据集。

我一直在尝试使用 prettytable,但没有找到任何指定如何制作第二个 header 适用于以下多个列的内容。

您可以编写一个函数来使用最大列宽对齐所有数据条目,如下所示:

def write_cols(data):
    col_spacer = "   "      # added between columns
    widths = [0] * len(data[0])

    # Calculate the widest entry for each column
    for row in data:
        widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]

    return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data]

data = [['', 'Config 1', '', 'Config 2', ''], ["Test", "Data 1", "Data 2", "Data 1", "Data 2"], ["abc", "123", "123", "123", "123"]]

for row in write_cols(data):
    print row

这将显示您的数据如下:

       Config 1            Config 2         
Test   Data 1     Data 2   Data 1     Data 2
abc    123        123      123        123