jef
jef

Reputation: 4075

Joint nested list in Python

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

Upvotes: 0

Views: 336

Answers (3)

f5r5e5d
f5r5e5d

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

Chen A.
Chen A.

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

Woody Pride
Woody Pride

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

Related Questions