Compare 2 lists of tuples with same size,:compare and swap

Viewed 39

Made 2 list of tuples: I wanna use the alphabet and the counter, for comparing both lists. Tuples of su, belong on the index of tuples in list tu. -> tuple 0 on tu has (40, 'b', 1) -> 'b', 1 in tuple 4 in su are the same, therefore tuple 4 of su should go to index 0, usw.

su = [(30, 'a', 1), (1, 'b', 0), (4, 'a', 0), (17, 'c', 0), (8, 'b', 1)]
tu = [(40, 'b', 1), (9, 'c', 0), (3, 'b', 0), (11, 'a', 0), (12, 'a', 1)]

for i, (s, t) in enumerate(zip(su, tu)):
             if t[1] == 'H':
                print(f" 'H' {i}")

My final wanted list su_new = [(8, b, 1), (17, 'c', 0), (1, 'b', 0), (4, 'a', 0), (30, 'a', 1)] For comparing, I filled in both lists, indices. [(8, b), (17, 'c'), (1, 'b'), (4, 'a'), (30, 'a')]

1 Answers

This works:

from copy import copy
su = [(30, 'a', 1), (1, 'b', 0), (4, 'a', 0), (17, 'c', 0), (8, 'b', 1)]
tu = [(40, 'b', 1), (9, 'c', 0), (3, 'b', 0), (11, 'a', 0), (12, 'a', 1)]

index_dic = {}
for i, tup in enumerate(tu):
    index_dic[tup[1:]] = i

new_su = copy(su)
for tup in su:
    new_index = index_dic[tup[1:]]
    new_su[new_index] = tup

print(new_su)
#[(8, 'b', 1), (17, 'c', 0), (1, 'b', 0), (4, 'a', 0), (30, 'a', 1)]

Alternatively, the index_dic can be constructed as a dictionary comprehension:

index_dic = {tup[1:]:i for i, tup in enumerate(tu)}
Related