Here’s a silly one-liner version:
def print_table(seq, width=3):
print('\n'.join([''.join(
[(str(u[-i]) if len(u) >= i else '').rjust(width) for u in seq])
for i in range(max(len(u) for u in seq), 0, -1)]))
And here’s the same algorithm in a somewhat more readable form:
def get_cell(u, i):
return str(u[-i]) if len(u) >= i else ''
def print_table(seq, width=3):
maxlen = max(len(u) for u in seq)
for i in range(maxlen, 0, -1):
row = [get_cell(u, i).rjust(width) for u in seq]
print(''.join(row))
#Test
lista=[[2], [1, 2], [2], [3], [3]]
listb=[[4], [2, 5], [1, 3, 6], [7], [8]]
print(lista)
print_table(lista)
print('-' * 20)
print(listb)
print_table(listb)
output
[[2], [1, 2], [2], [3], [3]]
1
2 2 2 3 3
--------------------
[[4], [2, 5], [1, 3, 6], [7], [8]]
1
2 3
4 5 6 7 8
I won’t explain exactly how this code works, since I suspect that this is a homework question.
1
solved Print elements of list horizontally [closed]