Printing Lists as Tabular Data

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

    Pure Python 3

    def print_table(data, cols, wide):
        '''Prints formatted data on columns of given width.'''
        n, r = divmod(len(data), cols)
        pat = '{{:{}}}'.format(wide)
        line = '\n'.join(pat * cols for _ in range(n))
        last_line = pat * r
        print(line.format(*data))
        print(last_line.format(*data[n*cols:]))
    
    data = [str(i) for i in range(27)]
    print_table(data, 6, 12)
    

    Will print

    0           1           2           3           4           5           
    6           7           8           9           10          11          
    12          13          14          15          16          17          
    18          19          20          21          22          23          
    24          25          26
    

提交回复
热议问题