Search code examples
python-3.xlistpython-itertools

In Python, transform a nested string list into another arrangement


Curious if there was a fancy way of transforming this array:

[[a0],
[b0, b1],
[c0, c1],
[d0, d1],
[e0],
[f0],
[g0]]

into this array:

[["", b0, c0, d0, "", "", ""],
 [a0, b1, c1, d1, e0, f0, g0]]

i.e. Matrix manipulation, zip, etc? The input list is a list of column headers. If there are multiple items in a column header, it is multi-lined header. The output list is transformed so that it can be printed.


Solution

  • Try:

    from itertools import zip_longest
    
    lst = [["a0"], ["b0", "b1"], ["c0", "c1"], ["d0", "d1"], ["e0"], ["f0"], ["g0"]]
    
    out = list(map(list, zip_longest(*(v[::-1] for v in lst), fillvalue="")))[::-1]
    
    print(out)
    

    Prints:

    [['', 'b0', 'c0', 'd0', '', '', ''], ['a0', 'b1', 'c1', 'd1', 'e0', 'f0', 'g0']]