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']]
jef
  • 3,890
  • 10
  • 42
  • 76

3 Answers3

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']]
Woody Pride
  • 13,539
  • 9
  • 48
  • 62
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']]
f5r5e5d
  • 3,656
  • 3
  • 14
  • 18
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])
Chen A.
  • 10,140
  • 3
  • 42
  • 61