Merge rows with identical indices in two lists

I have two lists, and I would like to combine them in 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, for example below

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

I'm trying to extend, zip, append, enumerate, but I can not get what I want. Two cycles repeat the result.

Any hint or elegant way to do this, please?

+4
source share
8 answers

Aand Bare lists of strings. Using zip, you can create type pairs ('1,2,3', '10'). Subsequently, you can combine these two lines 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
+6
source

','.join zip..

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

C = [ ','.join(pair) for pair in zip(A,B) ]
+5
[a + ',' + b for a, b in zip(A, B)]
+4

enumerate, zip

>>> A = ['1,2,3','4,5,6','7,8,9']
>>> B = ['10','11','12']
>>> [a + "," + B[i] for i, a in enumerate(A)]
['1,2,3,10', '4,5,6,11', '7,8,9,12']
+2

, - , A B - . -zip :

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

# basic solution using for/len, will except if len(A) > len(B)
>>> [ A[i] + "," + B[i] for i in range(len(A)) ]

# complicated solution to deal with a difference in the
# lengths of A and B 
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12']

# add something to A, len(A) > len(B)
>>> A.append('13,14,15')
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12', '13,14,15,']

# add a couple of things to B, len(B) > len(A)
>>> B.append('16')
>>> B.append('17')
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12', '13,14,15,16', ',,,17']
+2

map str.join :

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

from itertools import izip

print(map(",".join, izip(A, B)))
['1,2,3,10', '4,5,6,11', '7,8,9,12']
+2

, :

def concat_lists(l1, l2):
    concat_list = []
    for i in range(len(l1)):
        concat_list.append(l1[i] + ',' + l2[i])
    return concat_list

:

def concat_lists(l1, l2):
    return [l1[i] + ',' + l2[i] for i in range(len(l1))]
+2

map... , list of tuples zip..

>>> A = ['1,2,3','4,5,6','7,8,9']
>>> B = ['10','11','12']
>>> map(lambda x, y:x + ',' + y, A, B)
['1,2,3,10', '4,5,6,11', '7,8,9,12']
+1

Source: https://habr.com/ru/post/1618180/


All Articles