How do I print a list of numbers vertically?

Viewed 508

I am trying to solve an exercise. I should write a function that takes a list of integers, converts it to a string of numbers displayed vertically.

mylist = [5,69,2090]

the function should return/print the following string:

    2
    0
  6 9
5 9 0

I tried to solve it with the following code, but it doesn't help me

def printstring(mylist):
    h = len(mylist)//3
    for i in range(h):
        print(mylist[i],mylist[h+i],l[h+i+1])
4 Answers
lst = [5,69,2090]

n = max(len(str(i)) for i in lst)
for i in zip(*['{:>{n}}'.format(i, n=n) for i in lst]):
    print(' '.join(i))

Prints:

    2
    0
  6 9
5 9 0

For lst = [1,123,12,12345,1234]:

      1  
      2 1
  1   3 2
  2 1 4 3
1 3 2 5 4

First convert your list items to a string then find the maximum length. Pad your strings to fit that length and print them:

lst = [5, 69, 2090]
lst = list(map(str, lst))
max_lenght = max(map(len, lst))
padded_lst = [item.rjust(max_lenght, " ") for item in lst]
for row in zip(*padded_lst):
    print(" ".join(row))
    2
    0
  6 9
5 9 0

I'd apply a few steps here. First, determine the maximum length of digits for each number by converting them to strings. Secondly, left pad each number string to that length using rjust. Finally, rotate the matrix 90 degrees using the classic zip(*m) trick and join it all back into a printable square.

>>> lst = [5,69,2090]
>>> size = max(map(len, map(str, lst)))
>>> m = [str(x).rjust(size, " ") for x in lst]
>>> print("\n".join([" ".join(x) for x in zip(*m)]))
    2
    0
  6 9
5 9 0

A not so much readable two liner

sl = ['{:>{}d}'.format(s, len(str(max(mylist)))) for s in mylist]
print('\n'.join(' '.join(s) for s in zip(*sl))) 
Related