Search code examples
pythonlistpython-3.xsortingtranspose

Lists sorting in Python (transpose)


I have arbitrary lists, for instance here are three lists:

a = [1,1,1,1]
b = [2,2,2,2]
c = [3,3,3,3]

And I want transpose them together in order to get the output like this:

f_out = [1,2,3]
g_out = [1,2,3]
...
n_out = [1,2,3]

As, you can see, I just converted "columns" to "rows".

The issue is a solution has to be independent of the lists length.

For example:

a = [1,1]
b = [2]
c = [3,3,3]
# output
f_out = [1,2,3]
g_out = [1,3]
n_out = [3]

Solution

  • You can use zip_longest

    >>> from itertools import zip_longest
    >>> a = [1,1]
    >>> b = [2]
    >>> c = [3,3,3]
    >>> f,g,h=[[e for e in li if e is not None] for li in zip_longest(a,b,c)]
    >>> f
    [1, 2, 3]
    >>> g
    [1, 3]
    >>> h
    [3]
    

    If None is a potential valid value in the lists, use a sentinel object instead of the default None:

    >>> b = [None]
    >>> sentinel = object()
    >>> [[e for e in li if e is not sentinel] for li in zip_longest(a,b,c, fillvalue=sentinel)]
    [[1, None, 3], [1, 3], [3]]