Could somebody please tell me how can I merge the following list:
[[['a', 'b'], ['b', 'a'], ['c', 'c']], [['d', 'e'], ['e', 'd']]]
into:
[['ab', 'ba', 'cc'], ['de', 'ed']]
?
Thank you!
CodePudding user response:
IIUC, you need to map the join on all the sublists:
l = [[['a', 'b'], ['b', 'a'], ['c', 'c']], [['d', 'e'], ['e', 'd']]]
out = [list(map(''.join, x)) for x in l]
Or:
out = [[''.join(i) for i in x] for x in l
Output: [['ab', 'ba', 'cc'], ['de', 'ed']]
CodePudding user response:
Two methods:
- Use
map()
and''.join
:
data = [[['a', 'b'], ['b', 'a'], ['c', 'c']], [['d', 'e'], ['e', 'd']]]
result = [list(map(''.join, item)) for item in data]
print(result)
- Use a list comprehension:
data = [[['a', 'b'], ['b', 'a'], ['c', 'c']], [['d', 'e'], ['e', 'd']]]
result = [[''.join(item) for item in sublist] for sublist in data]
print(result)
Both of these print:
[['ab', 'ba', 'cc'], ['de', 'ed']]