Printing Lists as Tabular Data

后端 未结 14 2055
小蘑菇
小蘑菇 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:10

    A simple way to do this is to loop over all columns, measure their width, create a row_template for that max width, and then print the rows. It's not exactly what you are looking for, because in this case, you first have to put your headings inside the table, but I'm thinking it might be useful to someone else.

    table = [
        ["", "Man Utd", "Man City", "T Hotspur"],
        ["Man Utd", 1, 0, 0],
        ["Man City", 1, 1, 0],
        ["T Hotspur", 0, 1, 2],
    ]
    def print_table(table):
        longest_cols = [
            (max([len(str(row[i])) for row in table]) + 3)
            for i in range(len(table[0]))
        ]
        row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
        for row in table:
            print(row_format.format(*row))
    

    You use it like this:

    >>> print_table(table)
    
                Man Utd   Man City   T Hotspur
      Man Utd         1          0           0
     Man City         1          1           0
    T Hotspur         0          1           2
    

提交回复
热议问题