0

Sorry if this is a noob question.

i have a list, for exemple "a" which has two or tree list inside a1,a2,a3 like :

[ [1,2], [0,0,0], [1,2,3,4,5] ]
[ [1,2,3,4], [0,0], [1,2,3]   ]

etc...

Each list inside doesn't has the same length so when I make a simple

for i in range(len(a)):
    print(a[i])

the result is :

[[1,2],[0,0,0],[1,2,3,4,5]]
[[1,2,3,4],[0,0],[1,2,3]]

While I'm waiting for this result where elements in list are aligned in columns :

[[1,2]          [0,0,0]      [1,2,3,4,5]]
[[1,2,3,4]      [0,0]        [1,2,3]]

How can I do that?

thanks in advance for any help.

APhillips
  • 1,175
  • 9
  • 17
  • 1
    Does this answer your question? [Print Excel workbook using python](https://stackoverflow.com/questions/42751142/print-excel-workbook-using-python) – BpY Jan 22 '20 at 16:49
  • @BSQL this is completely not a duplicate. It is about actual printing (using a printer) of a file. OP asks about printing to the screen – Tomerikoo Jan 22 '20 at 17:00

2 Answers2

0

You can use string's ljust method to align the lists according to the largest:

a = [[[1, 2], [0, 0, 0], [1, 2, 3, 4, 5]],
     [[1, 2, 3, 4], [0, 0], [1, 2, 3]]]

size = max([len(str(x)) for sub in a for x in sub]) + 4

for sub in a:
    for x in sub:
        print(str(x).ljust(size), end="")
    print()

This Gives:

[1, 2]             [0, 0, 0]          [1, 2, 3, 4, 5]    
[1, 2, 3, 4]       [0, 0]             [1, 2, 3]   

Another option using one loop and the join method could be:

for sub in a:
    print(''.join((str(x).ljust(size) for x in sub)))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Another quick-and-dirty approach, using str.format:

a = [[ [1,2], [0,0,0], [1,2,3,4,5] ],
     [ [1,2,3,4], [0,0], [1,2,3]   ],
     [ [1], [2,2]],
     []]

max_sublist = max(a, key=len)
max_len = len(str(max((i for subl in a for i in subl), key=lambda k: len(str(k)))))

for subl in a:
    print('[{}]'.format(('{!s:<{width}}' * len(max_sublist)).format(*subl, *' '*len(max_sublist), width=max_len)))

Prints:

[[1, 2]         [0, 0, 0]      [1, 2, 3, 4, 5]]
[[1, 2, 3, 4]   [0, 0]         [1, 2, 3]      ]
[[1]            [2, 2]                        ]
[                                             ]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91