Reputation: 137
I have two list like these:
L1 = [(1, 'a'), (2, 'm'), (3, 'd') ....]
L2 = [('b', 1), ('f', 2), ('x', 1), ('w', 3), ('j', 2) ... ]
and I want to produce:
L3 = [('a','b'),('m','f'),('a','x'),('d','w'),('m','j'), ...]
I mean, where second element in tuple of list L1 match with first element in tuple of list L2.
L1 and L2 are above 12 millions of tuples.
I have a code that works using nested loops for comparison between 'keys' of each tuples but is fairly inefficient.
What could be a good alternative to do it in the faster way ?
Thank you in advance.
Upvotes: 2
Views: 636
Reputation: 15738
dictionaries have O(1) select/insert complexity. Use them:
L1_dict = dict(L1)
L3 = [(L1_dict[k], v) for v, k in L2 if k in L1_dict]
Upvotes: 5