pythonlistjoinnestedflat

Triple nested list to a list of string in python


I have a triple nested list and trying to grab the same position of the most inner list elements and join as a list of strings by the second nested level in python.

input=[[['a b c'], ['d e f'], ['g h i']], [['j k l'], ['m n o'], ['p q r']], [['s t u'], ['v w x'], ['y z zz']]]

output=['a b c j k l s t u', 'd e f m n o v w x', 'g h i p q r y z zz']

I found how to flatten the entire lists but in this case, I like to keep the second inner list. Any suggestions appreciated!


Solution

  • Try:

    inp = [
        [["a b c"], ["d e f"], ["g h i"]],
        [["j k l"], ["m n o"], ["p q r"]],
        [["s t u"], ["v w x"], ["y z zz"]],
    ]
    
    out = [" ".join(s for l in t for s in l) for t in zip(*inp)]
    print(out)
    

    Prints:

    ["a b c j k l s t u", "d e f m n o v w x", "g h i p q r y z zz"]