Home > Back-end >  Triple nested list to a list of string in python
Triple nested list to a list of string in python

Time:09-21

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!

CodePudding user response:

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"]

CodePudding user response:

You can use itertools.chain, map, and zip:

from itertools import chain
list(map(lambda x: ' '.join(chain(*x)), zip(*my_input)))

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']

NB. I named the input my_list

  • Related