Your answer is not bad, it is better than sorting the array at each iteration, but it is still O (N ^ 2).
Since you know the indexes of the arrays you want, you can use the quickselect algorithm to search for indexes 0,1,2 based on the magicComp function in O (log n). This will reduce the runtime to O (n * log n)
Based on the code in this link, your code will look something like this:
results = {} ls2 = list(set2) for el in set1: results[el] = [select(ls2, ii) for ii in [0,1,2]]
source share