0

Sorry to ask, probabily this is a simple question but I can't find a solution.

I have a list of lists, like this:

my_list = [['ba', 'da'], ['ra', 're'], ['ta', 'ma'], ]

the number of list is variable (3 in the example) but the lenght is the same for all of them (2 in the example).

I want:

new_list = ['barata', 'darema']

where

new_list[i] = my_list[0][i] + my_list[1][i] + my_list[2][i]
fabio
  • 1,210
  • 2
  • 26
  • 55
  • Can you include your attempt that came the closest to being what you need? – wwii Jan 05 '20 at 17:15
  • Can you please clarify this "I have string, not integer but probabily is the same"? – Andreas K. Jan 05 '20 at 17:19
  • @Andreas In my list I haven't integer (like in my example) but string. I hoped to be more clear using integer but probabily not because the solution don't works (TypeError: unsupported operand type(s) for +: 'int' and 'str') – fabio Jan 05 '20 at 17:30
  • @wwii not like that because I have string – fabio Jan 05 '20 at 17:30
  • `I hoped to be more clear using integer...` - You should always include a [mcve] that faithfully represents your problem. – wwii Jan 05 '20 at 17:37
  • @wwii sorry, I thinked it was faithfull – fabio Jan 05 '20 at 17:42
  • Other duplicate for edited question - [Element wise concatenate multiple lists (list of list of strings)](https://stackoverflow.com/questions/56479890/element-wise-concatenate-multiple-lists-list-of-list-of-strings) – wwii Jan 05 '20 at 18:10

2 Answers2

3

You can use zip to pack the unpacked items from my_list.

my_list = [[0, 1], [2, 3], [3, 2]]

my_list=list(map(sum,zip(*my_list)))

print(my_list)

output

[5,6]

if elements are str then use the below code.

my_list = [['ba', 'da'], ['ra', 're'], ['ta', 'ma'], ]

my_list=list(map(''.join,zip(*my_list)))

print(my_list)

output

['barata', 'darema']
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 1
    You don't have to use list() on zip(). – Andreas K. Jan 05 '20 at 17:22
  • 1
    @AndreasK. Yes, I realized it map just needs an iterable and edited it long back by the way. – Ch3steR Jan 05 '20 at 17:24
  • @Ch3steR thank you for your answer but for my fault it doesn't work: I have strings, not integers so it gives me this error: TypeError: unsupported operand type(s) for +: 'int' and 'str' – fabio Jan 05 '20 at 17:34
  • 3
    @fabio You edited the question. This answer was if elements were integers. I'll edit and add for `strings` too – Ch3steR Jan 05 '20 at 17:37
1
my_list = [['ba', 'da'], ['ra', 're'], ['ta', 'ma'], ]
[''.join(t) for t in zip(*my_list)]

Gives:

['barata', 'darema']
Andreas K.
  • 9,282
  • 3
  • 40
  • 45