'Merging only the sublists but not all of them into one list in Python
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!
Solution 1:[1]
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']]
Solution 2:[2]
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']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
| Solution 2 |
