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.

3
  • Does this answer your question? stackoverflow.com/questions/952914/… Commented Jun 17, 2020 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 Commented Jun 17, 2020 at 13:47
  • 1
    Oh yes sorry about that, Ill keep that in mind for next time! Commented Jun 17, 2020 at 13:52

4 Answers 4

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']]]
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, so for some reason Im getting an invalid syntax error. Im working in python 2 maybe thats why?
Updated @asiv - yes that's the reason
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!

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.