how to print dynamic 2D list in an aligned manner in python?

蹲街弑〆低调 提交于 2019-12-24 22:34:28

问题


I want to print a list while keeping its elements vertically aligned. Currently my code prints the list [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]] as

0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

Instead, I would like to print

 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

How can I achieve such a result without import anything? This is the code I've written so far:

for i in BoardSize:
    print(*i, end="\n")

回答1:


Maybe the package tabulate suits your needs.

Source: https://github.com/astanin/python-tabulate

Here an example:

from tabulate import tabulate

BoardSize = [
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [8, 9, 10, 11],
    [12, 13, 14, 15]]

print(tabulate(BoardSize, tablefmt="plain"))

Output:

 0   1   2   3
 4   5   6   7
 8   9  10  11
12  13  14  15

Edit without a package

A quick and dirty solution

BoardSize = [
    [0, 1, 2, 3],
    [4, 5, 6, 7],
    [8, 9, 10, 11],
    [12, 13, 14, 15]]


max_number_of_digits = 0
for row in BoardSize:
    for cell in row:
        number_of_digits = len(str(cell))
        if number_of_digits > max_number_of_digits:
            max_number_of_digits = number_of_digits


for row in BoardSize:
    print_row = ''
    for cell in row:
        # fill with space on the left side of the string
        # the padding has to be at least one higher than
        # the max_number_of_digits
        # the higher the number you add, the wider the padding
        print_row += f'{cell}'.rjust(max_number_of_digits + 1, ' ')

    print(print_row)


来源:https://stackoverflow.com/questions/58998222/how-to-print-dynamic-2d-list-in-an-aligned-manner-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!