A Text Table Writer/Printer for Python

后端 未结 2 1490
渐次进展
渐次进展 2020-12-16 18:18

TL;DR -> Is there a table writing module on PyPi (I\'ve failed to find any) that takes in lists as parameters and makes a table out of those

2条回答
  •  长情又很酷
    2020-12-16 18:34

    I’m just going to throw a solution from me in which I’ve actually written last week just to test something out. It currently right-aligns everything but it would be simple enough to add some alignment parameters or something.

    def printTable (tbl, borderHorizontal = '-', borderVertical = '|', borderCross = '+'):
        cols = [list(x) for x in zip(*tbl)]
        lengths = [max(map(len, map(str, col))) for col in cols]
        f = borderVertical + borderVertical.join(' {:>%d} ' % l for l in lengths) + borderVertical
        s = borderCross + borderCross.join(borderHorizontal * (l+2) for l in lengths) + borderCross
    
        print(s)
        for row in tbl:
            print(f.format(*row))
            print(s)
    

    Example:

    >>> x = [['Length', 'Time(ms)'], [0, 0], [250, 6], [500, 21], [750, 50], [1000, 87], [1250, 135], [1500, 196], [1750, 269], [2000, 351]]
    >>> printTable(x)
    +--------+----------+
    | Length | Time(ms) |
    +--------+----------+
    |      0 |        0 |
    +--------+----------+
    |    250 |        6 |
    +--------+----------+
    |    500 |       21 |
    +--------+----------+
    |    750 |       50 |
    +--------+----------+
    |   1000 |       87 |
    +--------+----------+
    |   1250 |      135 |
    +--------+----------+
    |   1500 |      196 |
    +--------+----------+
    |   1750 |      269 |
    +--------+----------+
    |   2000 |      351 |
    +--------+----------+
    

提交回复
热议问题