Given 2 tuples, perform cross pairing of corresponding tuples, convert to single tuple if 1st element of both tuple matches.
Input : test_list1 = [(1, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
Output : [(7, 3)]
Explanation : 1 occurs as tuple element at pos. 1 in both tuple, its 2nd elements are paired and returned.
Input : test_list1 = [(10, 7), (6, 7), (8, 100), (4, 21)], test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
Output : []
Explanation : NO pairing possible.
In this, we check for 1st element using conditional statements and, and construct new tuple in list comprehension.
OutputThe original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]
In this, the task of pairing is done using zip() and conditional check is done inside list comprehension.
OutputThe original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]
The approach uses a dictionary to store the tuples in list 1, with the first element as the key and the second element as the value. Then, it loops through each tuple in list 2 and checks if the first element of the tuple is a key in the dictionary. If it is, a tuple is appended to the mapped tuples list with the value of the key in the dictionary as the first element and the second element of the tuple in list 2 as the second element. Finally, the list of mapped tuples is returned.
1.Initialize an empty dictionary to store the tuples in list 1.
2.Loop through each tuple in list 1.
3.Add the tuple to the dictionary with the first element as the key and the second element as the value.
4.Initialize an empty list to store mapped tuples.
5.Loop through each tuple in list 2.
6.If the first element of the tuple in list 2 is a key in the dictionary, append a tuple of the value of the key in the dictionary and the second element of the tuple in list 2 to the mapped tuples list.
7.Return the mapped tuples list.