user3362571 - 1 year ago 91
Python Question

# How to make a list of lists display vertically

So I have a list L.

L = [[1],[2,3],[3,4,5]]

How would I go about to make it look like this.

1 2 3
3 4
5

I want this to be able to iterate.
I think the best way would be nested for loops, but I am confused on where to begin.

EDIT***

I managed to make something that resembles what I want to do.

L = [[1],[2,3],[3,4,5],[]]
max_list= []

maxlen=max(len(l) for l in L)
for row in range(maxlen):
max_list.append([])
for col in tab:
try:
max_list[row].append(col[row])
except:
max_list[row].append('')
for col in max_list:
print(col)

Output:

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

As of right now how would I format it to

1 2 3
3 4
5

Solutions are not so elegant, too much code...

L = [[1],[2,3],[3,4,5]]
max_length = max(map(len, L))  # finding max length
output = zip(*map(lambda x: x + [' '] * (max_length - len(x)), L))  # filling every sublist with ' ' to max_length and then zipping it
for i in output: print(*i)  # printing whole result

Output:

1 2 3
3 4
5

So 3rd line is not that obvious, i will break it down

>>> list(map(lambda x: x + [' '] * (max_length - len(x)), L))
[[1, ' ', ' '], [2, 3, ' '], [3, 4, 5]]
>>> list(zip(*map(lambda x: x + [' '] * (max_length - len(x)), L)))
[(1, 2, 3), (' ', 3, 4), (' ', ' ', 5)]

UPDATE

To lengthen the spaces you need to provide keyword argument sep to print function: for i in output: print(*i, sep= ' ')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download