I am trying to loop through and merge of two lists that look like this:
T1 = [[['a', 1], ['c', 3]], [['e', 5], ['g', 7]], [['i', 9],['j', 11]]]
T2 = [[['m', 1], ['n', 5]], [['q', 7], ['r', 7]], [['t', 9],['u', 11]]]
So for example, T1[0] = [['a', 1], ['c', 3]]
T2[0] = [['m', 1], ['n', 5]]
I am writing what is essentially a merge algorithm, where I compare the second element in each list in T1[0][0] (the 1), with the second value in T2[0][0] (so 1 again). Essentially what I want is T1[0][0][0] and T2[0][0][0]. If they match, I merge the two values into a tuple {'a', 1, 'm'} (can also be a list if it makes things easier).
My confusion is stemming from the fact that I don't know how to best loop through T1 and T2 without running it 3 times: (T1[0], T2[0]), (T1[1], T2[1]), (T1[2], T2[2])
Is there a way to elegantly loop through T1 and T2 so that I can go through each sublist in T1 and T2 and perform the check and merge?
Note: the data is already sorted, and I am not looking to use libraries. I want to know if I can do this myself.
##Update##
So I know it is a for loop, however the below code is as far as i can get, and it is throwing me a list index out of range as shown below
result = []
i = j = 0
while True:
for s_T1 in T1:
for s_T2 in T2:
if s_T1[i][1] < s_T2[j][1]: ### error at this line
i = i + 1
elif s_T1[i][1] > s_T2[j][1]:
j = j + 1
elif s_T1[i][1] == s_T2[j][1]:
result.append(s_T1[i][0], str(s_T1[i][0), s_T2[j][0])
i = i + 1
j = j + 1
if i == len(T1) or j == len(T2):
break
return result
What the code should return is:
[[['a', 1, 'm']], [['g', 7, 'q'], ['g', 7, 'r']], [['i', 9, 't'], ['j', 11, 'u']]]
So, look at the integer in ['e', 5] in T1, compare it to ['q', 7] in T2, since 5 is smaller than 7, move to the next value in T1. if they match, append. And the other way around - if the value in T1 is greater than the value in T2, move to the next value in T1.
['e', 5, 'n']are not in the same "index" in both of the lists, is this a mistake, or should each index inT1be compared against each index ofT2?['g', 7, 'q']shouldn't be there either correct?