Skip to content Skip to sidebar Skip to footer

Python - Transposing A List (rows With Different Length) Using Numpy Fails

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 contain

Solution 1:

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

Solution 2:

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)

Post a Comment for "Python - Transposing A List (rows With Different Length) Using Numpy Fails"