How do I output lists as a table in Jupyter notebook?

后端 未结 11 1051
灰色年华
灰色年华 2021-01-30 09:51

I know that I\'ve seen some example somewhere before but for the life of me I cannot find it when googling around.

I have some rows of data:

data = [[1,2         


        
11条回答
  •  猫巷女王i
    2021-01-30 10:39

    Ok, so this was a bit harder than I though:

    def print_matrix(list_of_list):
        number_width = len(str(max([max(i) for i in list_of_list])))
        cols = max(map(len, list_of_list))
        output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
        for row in list_of_list:
            for column in row:
                output += '|' + ' {:^{width}d} '.format(column, width = number_width)
            output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
        return output
    

    This should work for variable number of rows, columns and number of digits (for numbers)

    data = [[1,2,30],
            [4,23125,6],
            [7,8,999],
            ]
    print print_matrix(data)
    >>>>+-------+-------+-------+
        |   1   |   2   |  30   |
        +-------+-------+-------+
        |   4   | 23125 |   6   |
        +-------+-------+-------+
        |   7   |   8   |  999  |
        +-------+-------+-------+
    

提交回复
热议问题