I need to merge elements of sublist in python

  • A+
Category:Languages

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) 

 


If you are sure data1 and data2 always have same number of elements (sublists) you could use map following way:

data1 = [[4,5,9],[4,7,2],[11,13,15]] data2 = [[1,2,3,7],[3,6,8,5],[12,10,15,17]] data = list(map(lambda x,y:x+y,data1,data2)) print(data) 

output:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: