2

When the list contains only rows with same length the transposition works:

numpy.array([[1, 2], [3, 4]]).T.tolist();
>>> [[1, 3], [2, 4]]

But, in my case the list contains rows with different length:

numpy.array([[1, 2, 3], [4, 5]]).T.tolist();

which fails. Any possible solution?

DimChtz
  • 4,043
  • 2
  • 21
  • 39
  • What do you imagine the output of transposing `[[1,2],[3,4,5]]` to be? – Alec Jul 19 '16 at 19:00
  • @Alec In my case for `[[1, 2, 3], [4, 5]]`, I expect `[[1,4],[2,5],[3]]` (obviously) – DimChtz Jul 19 '16 at 19:02
  • is numpy a requirement? – David Bern Jul 19 '16 at 19:04
  • @DavidRobertsson Of course not, any solution is welcomed. – DimChtz Jul 19 '16 at 19:05
  • @DimChtz Obviously that is what you want for your sample input - I was suggesting that what you want might not make sense for a lot of other inputs (including the one I suggested). – Alec Jul 19 '16 at 19:06
  • @Alec Ohh, I see what you mean. Didn't see that coming :P – DimChtz Jul 19 '16 at 19:07
  • 1
    For numpy arrays with rows of different lengths, the individual elements are lists, not numpy arrays. For instance compare `J = np.array([[1, 2, 3], [4, 5]]); type(J[0])` with `J = np.array([[1, 2, 3], [4, 5, 6]]); type(J[0])`. – p-robot Jul 19 '16 at 19:15

2 Answers2

6

If you're not having numpy as a compulsory requirement, you can use itertools.zip_longest to do the transpose:

from itertools import zip_longest

l = [[1, 2, 3], [4, 5]]
r = [list(filter(None,i)) for i in zip_longest(*l)]
print(r)
# [[1, 4], [2, 5], [3]]

zip_longest pads the results with None due to unmatching lengths, so the list comprehension and filter(None, ...) is used to remove the None values

In python 2.x it would be itertools.izip_longest

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Using all builtins...

l = [[1, 2, 3], [4, 5]]
res = [[] for _ in range(max(len(sl) for sl in l))]

for sl in l:
    for x, res_sl in zip(sl, res):
        res_sl.append(x)
Alex
  • 18,484
  • 8
  • 60
  • 80