Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings at the same indexes in two lists

I have two lists and I'd like to combine them following the same order.

Below is the question.

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

To get a new list such as below

A+B = ['1,2,3,10','4,5,6,11','7,8,9,12']

I try extend, zip, append, enumerate but could not get what I want. Two loops the result will repeat.

Any hint or elegant way to do this please?

like image 683
Sakura Avatar asked Dec 01 '15 21:12

Sakura


2 Answers

A and B are lists of strings. Using zip, you can create pairs like ('1,2,3', '10'). Afterwards you can combine these two strings using join.

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

C = [','.join(z) for z in zip(A, B)]
print C
like image 143
Jakube Avatar answered Oct 04 '22 12:10

Jakube


Just use ','.join and zip..

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

C = [ ','.join(pair) for pair in zip(A,B) ]
like image 41
Chad S. Avatar answered Oct 04 '22 10:10

Chad S.