How to print a list more nicely?

前端 未结 22 1289
北荒
北荒 2020-12-01 09:34

This is similar to How to print a list in Python “nicely”, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even b

22条回答
  •  情话喂你
    2020-12-01 10:15

    this one prints list in separate columns (order is preserved)

    from itertools import zip_longest
    
    def ls(items, n_cols=2, pad=30):
        if len(items) == 0:
            return
        total = len(items)
        chunk_size = total // n_cols
        if chunk_size * n_cols < total:
            chunk_size += 1
        start = range(0, total, chunk_size)
        end = range(chunk_size, total + chunk_size, chunk_size)
        groups = (items[s:e] for s, e in zip(start, end))
        for group in zip_longest(*groups, fillvalue=''):
            template = (' ').join(['%%-%ds' % pad] * len(group))
            print(template % group)
    

    usage:

    ls([1, 2, 3, 4, 5, 6, 7], n_cols=3, pad=10)
    

    output:

    1          4          7         
    2          5                    
    3          6                    
    

    note that there may be missing columns if there is not enough number of items, because columns are filled first.

    ls([1, 2, 3, 4, 5], n_cols=4)
    

    output:

    1          3          5         
    2          4    
    

提交回复
热议问题