1

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.

yatu
  • 86,083
  • 12
  • 84
  • 139
Asiv
  • 115
  • 6
  • Does this answer your question? https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists – PApostol Jun 17 '20 at 13:29
  • I really enjoyed your recent questions, but would it be possible to format your list as strings? because we all had to manually do it – Nicolas Gervais Jun 17 '20 at 13:47
  • 1
    Oh yes sorry about that, Ill keep that in mind for next time! – Asiv Jun 17 '20 at 13:52

4 Answers4

3

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']]]
yatu
  • 86,083
  • 12
  • 84
  • 139
2

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!

panadestein
  • 1,241
  • 10
  • 21
2

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']]]
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
1

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']]]
George Udosen
  • 906
  • 1
  • 13
  • 28