0

How to convert a nested list like below?

d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]
-> [['a','b','c'], ['d','e','f']]

I found a similar question. But it's a little different. join list of lists in python [duplicate]

Update

Mine is not smart

new = []

for elm in d:
    tmp = []
    for e in elm:
         for ee in e:
              tmp.append(ee)
    new.append(tmp)

print(new)
[['a', 'b', 'c'], ['d', 'e', 'f']]
3
  • 1
    show us your attempt Commented Oct 9, 2017 at 19:12
  • I added my solution. Commented Oct 9, 2017 at 19:17
  • 2
    Possible duplicate of Flatten (an irregular) list of lists Commented Oct 9, 2017 at 19:19

3 Answers 3

2

Lots of ways to do this, but one way is with chain

from itertools import chain
[list(chain(*x)) for x in d]

results in:

[['a', 'b', 'c'], ['d', 'e', 'f']]
Sign up to request clarification or add additional context in comments.

2 Comments

The range(len(...) indirection seems unnecessary. [list(chain(*x)) for x in d] would be enough.
True, for some reason I gravitate to iterating over index rather than items, but changed answer as it is much easier.
1

sum(ls, []) to flatten a list has issues, but for short lists its just too concise to not mention

d = [[['a','b'], ['c']], [['d'], ['e', 'f']]]

[sum(ls, []) for ls in d]

Out[14]: [['a', 'b', 'c'], ['d', 'e', 'f']]

1 Comment

This is also nice!
0

This is a simple solution for your question

new_d = []
for inner in d:
    new_d.append([item for x in inner for item in x])

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.