Printing Lists as Tabular Data

后端 未结 14 2363
小蘑菇
小蘑菇 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 06:59

    I found this just looking for a way to output simple columns. If you just need no-fuss columns, then you can use this:

    print("Titlex\tTitley\tTitlez")
    for x, y, z in data:
        print(x, "\t", y, "\t", z)
    

    EDIT: I was trying to be as simple as possible, and thereby did some things manually instead of using the teams list. To generalize to the OP's actual question:

    #Column headers
    print("", end="\t")
    for team in teams_list:
        print(" ", team, end="")
    print()
    # rows
    for team, row in enumerate(data):
        teamlabel = teams_list[team]
        while len(teamlabel) < 9:
            teamlabel = " " + teamlabel
        print(teamlabel, end="\t")
        for entry in row:
            print(entry, end="\t")
        print()
    

    Ouputs:

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

    But this no longer seems any more simple than the other answers, with perhaps the benefit that it doesn't require any more imports. But @campkeith's answer already met that and is more robust as it can handle a wider variety of label lengths.

提交回复
热议问题