Home > Blockchain >  Merging only the sublists but not all of them into one list in Python
Merging only the sublists but not all of them into one list in Python

Time:03-14

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:

  1. 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)
  1. 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']]
  • Related