Asiv
Asiv

Reputation: 115

Flatten inner lists within nested list

I have sublists that contain internal nested lists per each sublist and I'd like to only flatten the internal nested list, so its just part of the sublist.

The list goes,

A=[[[[a ,b], [e ,f]], [e, g]],
   [[[d, r], [d, g]], [l, m]],
   [[[g, d], [e, r]], [g, t]]]

I'd like to flatten the nested list that appears in the first position of each sublist in A so the output looks like this,

A= [[[a ,b], [e ,f], [e, g]],
    [[d, r], [d, g], [l, m]],
    [[g, d], [e, r], [g, t]]]

Im not sure what code to use to do this, so any help is appreciated.

Upvotes: 1

Views: 150

Answers (4)

George Udosen
George Udosen

Reputation: 936

A little verbose but works:

import itertools

container = [list(itertools.chain(i[0] + [i[1]])) for i in A]

print(container)

Result:

[[['a', 'b'], ['e', 'f'], ['e', 'g']], 
 [['d', 'r'], ['d', 'g'], ['l', 'm']], 
 [['g', 'd'], ['e', 'r'], ['g', 't']]]

Upvotes: 1

Nicolas Gervais
Nicolas Gervais

Reputation: 36624

I think this is as simple as it gets:

[*map(lambda x: x[0] + [x[1]], A)]
[[['a', 'b'], ['e', 'f'], ['e', 'g']],
 [['d', 'r'], ['d', 'g'], ['l', 'm']],
 [['g', 'd'], ['e', 'r'], ['g', 't']]]

Upvotes: 2

panadestein
panadestein

Reputation: 1291

Try this:

B = [[*el[0], el[1]] for el in A]
print(B)

Output:

[[['a', 'b'], ['e', 'f'], ['e', 'g']],
 [['d', 'r'], ['d', 'g'], ['l', 'm']],
 [['g', 'd'], ['e', 'r'], ['g', 't']]]

Alternatively, for Python 2 (the star * operator does not behave in the same way here):

B = list(map(lambda x: [x[0][0], x[0][1], x[1]], A))

You can Try it online!

Upvotes: 2

yatu
yatu

Reputation: 88236

You could use a list comprehension with unpacking to flatten that first inner list:

A[:] = [[*i, j] for i,j in A]

For pythons older than 3.0:

[i+[j] for i,j in A]

print(A)

[[['a', 'b'], ['e', 'f'], ['e', 'g']],
 [['d', 'r'], ['d', 'g'], ['l', 'm']],
 [['g', 'd'], ['e', 'r'], ['g', 't']]]

Upvotes: 3

Related Questions