Printing Lists as Tabular Data

后端 未结 14 2099
小蘑菇
小蘑菇 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条回答
  •  Happy的楠姐
    2020-11-21 07:22

    The following function will create the requested table (with or without numpy) with Python 3 (maybe also Python 2). I have chosen to set the width of each column to match that of the longest team name. You could modify it if you wanted to use the length of the team name for each column, but will be more complicated.

    Note: For a direct equivalent in Python 2 you could replace the zip with izip from itertools.

    def print_results_table(data, teams_list):
        str_l = max(len(t) for t in teams_list)
        print(" ".join(['{:>{length}s}'.format(t, length = str_l) for t in [" "] + teams_list]))
        for t, row in zip(teams_list, data):
            print(" ".join(['{:>{length}s}'.format(str(x), length = str_l) for x in [t] + row]))
    
    teams_list = ["Man Utd", "Man City", "T Hotspur"]
    data = [[1, 2, 1],
            [0, 1, 0],
            [2, 4, 2]]
    
    print_results_table(data, teams_list)
    

    This will produce the following table:

                Man Utd  Man City T Hotspur
      Man Utd         1         2         1
     Man City         0         1         0
    T Hotspur         2         4         2
    

    If you want to have vertical line separators, you can replace " ".join with " | ".join.

    References:

    • lots about formatting https://pyformat.info/ (old and new formatting styles)
    • the official Python tutorial (quite good) - https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method
    • official Python information (can be difficult to read) - https://docs.python.org/3/library/string.html#string-formatting
    • Another resource - https://www.python-course.eu/python3_formatted_output.php

提交回复
热议问题