Chaban33
Chaban33

Reputation: 1382

merge 2 lists with tuple and list and integer

I have 2 lists with tuple and list inside them, how could I merge them together that result would be like this

values 6,0 never changes, only values like 3120 can change alost ther can bet multiple integers in the second list like list1 = [(6, 0, [3120,2121,14141])]

list3 = [(6, 0, [3120, 3116])]

my lists

list1 =  [(6, 0, [3120])]

and

list2 = [(6, 0, [3116])]

Upvotes: 0

Views: 78

Answers (4)

bkawan
bkawan

Reputation: 1361

You can do as below assuming length of list1 and list 2 are equal.


list1 =  [(6, 0, [2,4,8]),(3, 5, [3,5,7]),]
list2 =  [(6, 0, [10,12,14]),(3, 5, [9,11,13,15]),]

final_list = []

for i, v in enumerate(list1):
    list3 = [(list1[i])] + [(list2[i])]
    final = list3[0][:2] + tuple([list3[0][2] + list3[1][2]])
    final_list.append(final)
print(final_list)
Out[1]: [(6, 0, [2, 4, 8, 10, 12, 14]), 
         (3, 5, [3, 5, 7, 9, 11, 13, 15])]

Upvotes: 1

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

You can try it this way, provided the first two items in the tuple won't change as per the question.


list1 =  [(6, 0, [3120])]
list2 = [(6, 0, [3116])]

def add_two_lists(list1, list2):
    # Destructure the first element which is a tuple in both lists
    l1_first, l1_second, rest_first = list1[0]
    l2_first, l2second, rest_second = list2[0]
    res_tuple = (l1_first, l1_second, rest_first + rest_second)
    res_list = [res_tuple]
    return res_list

print(add_two_lists(list1, list2))

Upvotes: 1

Austin
Austin

Reputation: 26039

You can do this for your example input:

list3 = [list1[0][:2] + tuple([list1[0][2] + list2[0][2]])]
# [(6, 0, [3120, 3116])]

Works for multiple values in the list:

list1 = [(6, 0, [3120,2121,14141])]
list2 = [(6, 0, [3116])]

list3 = [list1[0][:2] + tuple([list1[0][2] + list2[0][2]])]

print(list3)
# [(6, 0, [3120, 2121, 14141, 3116])]

Upvotes: 1

Ashu Grover
Ashu Grover

Reputation: 757

This should do the trick for you:

list1 =  [(6, 0, [3120])]

list2 = [(6, 0, [3116])]

temp_list1 = list(list1[0])

temp_list2 = list(list2[0])

temp_list1[2].append(temp_list2[2][0])

final_tuple= tuple(temp_list1)

list3=[]
list3.append(final_tuple)

print(list3)

prints:

[(6, 0, [3120, 3116])]

Upvotes: 1

Related Questions