Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to merge elements of sublist in python

i have following data lists

data1 = [[4,5,9],[4,7,2],[11,13,15]]
data2 = [[1,2,3,7],[3,6,8,5],[12,10,15,17]]

i want the merging of list to be done as follows.

data = [[4,5,9,1,2,3,7], [4,7,2,3,6,8,5], [11,13,15,12,10,15,17]]

i.e. merging the elements at index 0 in data1 and data2 and merging the elements at index 1 in data1 and data 2 and so on..

data1 = [[4,5,9],[4,7,2],[11,13,15]]
data2 = [[1,2,3,7],[3,6,8,5],[12,10,15,17]]
for i in range (0,2):
    for j in range(0,3):
        data1[i].extend(data2[j])
print(data1)
like image 245
Mahi S Avatar asked Feb 09 '19 09:02

Mahi S


1 Answers

Use zip() with list-comprehension:

data1 = [[4,5,9],[4,7,2],[11,13,15]] 
data2 = [[1,2,3,7],[3,6,8,5],[12,10,15,17]]

data = [x+y for x, y in zip(data1, data2)]
# [[4, 5, 9, 1, 2, 3, 7], [4, 7, 2, 3, 6, 8, 5], [11, 13, 15, 12, 10, 15, 17]]


If you need it in normal loops way, you can get rid of one loop in your code (assuming both lists are of equal length):
data1 = [[4,5,9],[4,7,2],[11,13,15]]
data2 = [[1,2,3,7],[3,6,8,5],[12,10,15,17]]

for i in range(len(data1)):
    data1[i].extend(data2[i])

print(data1)
# [[4, 5, 9, 1, 2, 3, 7], [4, 7, 2, 3, 6, 8, 5], [11, 13, 15, 12, 10, 15, 17]]
like image 78
Austin Avatar answered Sep 28 '22 06:09

Austin