How to extend pretty print module to tables?

前端 未结 4 1899
傲寒
傲寒 2020-12-22 13:40

I have the pretty print module, which I prepared because I was not happy the pprint module produced zillion lines for list of numbers which had one list of list. Here is exa

相关标签:
4条回答
  • 2020-12-22 14:03

    My answer to this kind of regular cases would be to use this module: prettytable A simple Python library for easily displaying tabular data in a visually appealing ASCII table format

    0 讨论(0)
  • 2020-12-22 14:08

    If you're looking for nice formatting for matrices, numpy's output looks great right out of the box:

    from numpy import *
    print array([[i + j for i in range(10)] for j in range(10)])
    

    Output:

    [[ 0  1  2  3  4  5  6  7  8  9]
     [ 1  2  3  4  5  6  7  8  9 10]
     [ 2  3  4  5  6  7  8  9 10 11]
     [ 3  4  5  6  7  8  9 10 11 12]
     [ 4  5  6  7  8  9 10 11 12 13]
     [ 5  6  7  8  9 10 11 12 13 14]
     [ 6  7  8  9 10 11 12 13 14 15]
     [ 7  8  9 10 11 12 13 14 15 16]
     [ 8  9 10 11 12 13 14 15 16 17]
     [ 9 10 11 12 13 14 15 16 17 18]]
    
    0 讨论(0)
  • 2020-12-22 14:14

    Using George Sakkis' table indention recipe:

    print(indent(((i + j for i in range(10)) for j in range(10)),
                 delim=' ', justify='right'))
    

    yields:

    0  1  2  3  4  5  6  7  8  9
    1  2  3  4  5  6  7  8  9 10
    2  3  4  5  6  7  8  9 10 11
    3  4  5  6  7  8  9 10 11 12
    4  5  6  7  8  9 10 11 12 13
    5  6  7  8  9 10 11 12 13 14
    6  7  8  9 10 11 12 13 14 15
    7  8  9 10 11 12 13 14 15 16
    8  9 10 11 12 13 14 15 16 17
    9 10 11 12 13 14 15 16 17 18
    

    PS. To get the above to work, I made one minor change to the recipe. I changed wrapfunc(item) to wrapfunc(str(item)):

    def rowWrapper(row):
        newRows = [wrapfunc(str(item)).split('\n') for item in row]
    
    0 讨论(0)
  • 2020-12-22 14:15

    You can write:

    '\n'.join(  # join the lines with '\n'
           ' '.join(  # join one line with ' '
                  "%2d" % (i + j) # format each item
            for i in range(10))
        for j in range(10))
    
    0 讨论(0)
提交回复
热议问题