How to print a list more nicely?

前端 未结 22 1306
北荒
北荒 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 09:59

    Here's a solution in python 3.4 that automatically detects terminal width and takes it into account. Tested on Linux and Mac.

    def column_print(list_to_print, column_width=40):
        import os
        term_height, term_width = os.popen('stty size', 'r').read().split()
        total_columns = int(term_width) // column_width
        total_rows = len(list_to_print) // total_columns
        # ceil
        total_rows = total_rows + 1 if len(list_to_print) % total_columns != 0 else total_rows
    
        format_string = "".join(["{%d:<%ds}" % (c, column_width) \
                for c in range(total_columns)])
        for row in range(total_rows):
            column_items = []
            for column in range(total_columns):
                # top-down order
                list_index = row + column*total_rows
                # left-right order
                #list_index = row*total_columns + column
                if list_index < len(list_to_print):
                    column_items.append(list_to_print[list_index])
                else:
                    column_items.append("")
            print(format_string.format(*column_items))
    

提交回复
热议问题