Reputation: 4075
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]
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']]
Upvotes: 0
Views: 336
Reputation: 3706
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']]
Upvotes: 1
Reputation: 11280
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])
Upvotes: 0
Reputation: 13955
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']]
Upvotes: 2