Printing Lists as Tabular Data

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

    I know that I am late to the party, but I just made a library for this that I think could really help. It is extremely simple, that's why I think you should use it. It is called TableIT.

    Basic Use

    To use it, first follow the download instructions on the GitHub Page.

    Then import it:

    import TableIt
    

    Then make a list of lists where each inner list is a row:

    table = [
        [4, 3, "Hi"],
        [2, 1, 808890312093],
        [5, "Hi", "Bye"]
    ]
    

    Then all you have to do is print it:

    TableIt.printTable(table)
    

    This is the output you get:

    +--------------------------------------------+
    | 4            | 3            | Hi           |
    | 2            | 1            | 808890312093 |
    | 5            | Hi           | Bye          |
    +--------------------------------------------+
    

    Field Names

    You can use field names if you want to (if you aren't using field names you don't have to say useFieldNames=False because it is set to that by default):

    
    TableIt.printTable(table, useFieldNames=True)
    

    From that you will get:

    +--------------------------------------------+
    | 4            | 3            | Hi           |
    +--------------+--------------+--------------+
    | 2            | 1            | 808890312093 |
    | 5            | Hi           | Bye          |
    +--------------------------------------------+
    

    There are other uses to, for example you could do this:

    import TableIt
    
    myList = [
        ["Name", "Email"],
        ["Richard", "richard@fakeemail.com"],
        ["Tasha", "tash@fakeemail.com"]
    ]
    
    TableIt.print(myList, useFieldNames=True)
    

    From that:

    +-----------------------------------------------+
    | Name                  | Email                 |
    +-----------------------+-----------------------+
    | Richard               | richard@fakeemail.com |
    | Tasha                 | tash@fakeemail.com    |
    +-----------------------------------------------+
    

    Or you could do:

    import TableIt
    
    myList = [
        ["", "a", "b"],
        ["x", "a + x", "a + b"],
        ["z", "a + z", "z + b"]
    ]
    
    TableIt.printTable(myList, useFieldNames=True)
    

    And from that you get:

    +-----------------------+
    |       | a     | b     |
    +-------+-------+-------+
    | x     | a + x | a + b |
    | z     | a + z | z + b |
    +-----------------------+
    

    Colors

    You can also use colors.

    You use colors by using the color option (by default it is set to None) and specifying RGB values.

    Using the example from above:

    import TableIt
    
    myList = [
        ["", "a", "b"],
        ["x", "a + x", "a + b"],
        ["z", "a + z", "z + b"]
    ]
    
    TableIt.printTable(myList, useFieldNames=True, color=(26, 156, 171))
    

    Then you will get:

    Please note that printing colors might not work for you but it does works the exact same as the other libraries that print colored text. I have tested and every single color works. The blue is not messed up either as it would if using the default 34m ANSI escape sequence (if you don't know what that is it doesn't matter). Anyway, it all comes from the fact that every color is RGB value rather than a system default.

    More Info

    For more info check the GitHub Page

    0 讨论(0)
  • 2020-11-21 07:15

    I think this is what you are looking for.

    It's a simple module that just computes the maximum required width for the table entries and then just uses rjust and ljust to do a pretty print of the data.

    If you want your left heading right aligned just change this call:

     print >> out, row[0].ljust(col_paddings[0] + 1),
    

    From line 53 with:

     print >> out, row[0].rjust(col_paddings[0] + 1),
    
    0 讨论(0)
  • 2020-11-21 07:16

    There are some light and useful python packages for this purpose:

    1. tabulate: https://pypi.python.org/pypi/tabulate

    from tabulate import tabulate
    print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
    
    Name      Age
    ------  -----
    Alice      24
    Bob        19
    

    tabulate has many options to specify headers and table format.

    print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age'], tablefmt='orgtbl'))
    
    | Name   |   Age |
    |--------+-------|
    | Alice  |    24 |
    | Bob    |    19 |
    

    2. PrettyTable: https://pypi.python.org/pypi/PrettyTable

    from prettytable import PrettyTable
    t = PrettyTable(['Name', 'Age'])
    t.add_row(['Alice', 24])
    t.add_row(['Bob', 19])
    print(t)
    
    +-------+-----+
    |  Name | Age |
    +-------+-----+
    | Alice |  24 |
    |  Bob  |  19 |
    +-------+-----+
    

    PrettyTable has options to read data from csv, html, sql database. Also you are able to select subset of data, sort table and change table styles.

    3. texttable: https://pypi.python.org/pypi/texttable

    from texttable import Texttable
    t = Texttable()
    t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]])
    print(t.draw())
    
    +-------+-----+
    | Name  | Age |
    +=======+=====+
    | Alice | 24  |
    +-------+-----+
    | Bob   | 19  |
    +-------+-----+
    

    with texttable you can control horizontal/vertical align, border style and data types.

    4. termtables: https://github.com/nschloe/termtables

    import termtables as tt
    
    string = tt.to_string(
        [["Alice", 24], ["Bob", 19]],
        header=["Name", "Age"],
        style=tt.styles.ascii_thin_double,
        # alignment="ll",
        # padding=(0, 1),
    )
    print(string)
    
    +-------+-----+
    | Name  | Age |
    +=======+=====+
    | Alice | 24  |
    +-------+-----+
    | Bob   | 19  |
    +-------+-----+
    

    with texttable you can control horizontal/vertical align, border style and data types.

    Other options:

    • terminaltables Easily draw tables in terminal/console applications from a list of lists of strings. Supports multi-line rows.
    • asciitable Asciitable can read and write a wide range of ASCII table formats via built-in Extension Reader Classes.
    0 讨论(0)
  • 2020-11-21 07:21

    Updating Sven Marnach's answer to work in Python 3.4:

    row_format ="{:>15}" * (len(teams_list) + 1)
    print(row_format.format("", *teams_list))
    for team, row in zip(teams_list, data):
        print(row_format.format(team, *row))
    
    0 讨论(0)
  • 2020-11-21 07:22

    Python actually makes this quite easy.

    Something like

    for i in range(10):
        print '%-12i%-12i' % (10 ** i, 20 ** i)
    

    will have the output

    1           1           
    10          20          
    100         400         
    1000        8000        
    10000       160000      
    100000      3200000     
    1000000     64000000    
    10000000    1280000000  
    100000000   25600000000
    1000000000  512000000000
    

    The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.

    In this case I used "%-12i" twice. To break down each part:

    '-' (left align)
    '12' (how much space to be given to this part of the output)
    'i' (we are printing an integer)
    

    From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题