aby
aby

Reputation: 17

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

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")

Upvotes: 0

Views: 208

Answers (1)

Derrien
Derrien

Reputation: 51

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)

Upvotes: 1

Related Questions