Printing Lists as Tabular Data

后端 未结 14 2077
小蘑菇
小蘑菇 2020-11-21 06:38

I am quite new to Python and I am now struggling with formatting my data nicely for printed output.

I have one list that is used for two headings, and a matrix that

14条回答
  •  误落风尘
    2020-11-21 07:22

    When I do this, I like to have some control over the details of how the table is formatted. In particular, I want header cells to have a different format than body cells, and the table column widths to only be as wide as each one needs to be. Here's my solution:

    def format_matrix(header, matrix,
                      top_format, left_format, cell_format, row_delim, col_delim):
        table = [[''] + header] + [[name] + row for name, row in zip(header, matrix)]
        table_format = [['{:^{}}'] + len(header) * [top_format]] \
                     + len(matrix) * [[left_format] + len(header) * [cell_format]]
        col_widths = [max(
                          len(format.format(cell, 0))
                          for format, cell in zip(col_format, col))
                      for col_format, col in zip(zip(*table_format), zip(*table))]
        return row_delim.join(
                   col_delim.join(
                       format.format(cell, width)
                       for format, cell, width in zip(row_format, row, col_widths))
                   for row_format, row in zip(table_format, table))
    
    print format_matrix(['Man Utd', 'Man City', 'T Hotspur', 'Really Long Column'],
                        [[1, 2, 1, -1], [0, 1, 0, 5], [2, 4, 2, 2], [0, 1, 0, 6]],
                        '{:^{}}', '{:<{}}', '{:>{}.3f}', '\n', ' | ')
    

    Here's the output:

                       | Man Utd | Man City | T Hotspur | Really Long Column
    Man Utd            |   1.000 |    2.000 |     1.000 |             -1.000
    Man City           |   0.000 |    1.000 |     0.000 |              5.000
    T Hotspur          |   2.000 |    4.000 |     2.000 |              2.000
    Really Long Column |   0.000 |    1.000 |     0.000 |              6.000
    

提交回复
热议问题