Search List Optimization

first = [(1, text, text, 1, 2, 3), (1, text, text, 1, 0, 3), ... (6054, text, text, 2, 2, 3)] second = (1, 2, 3, 4, 5 ... 5412) 

Is there a faster way to do this:

 data = [x for x in first if x[0] in second] 
+4
source share
2 answers

Try the following:

 first = [(1, text, text, 1, 2, 3), (1, text, text, 1, 0, 3), ... (1054, text, text, 2, 2, 3)] second = (1, 2, 3, 4, 5 ... 5412) second_set = set(second) data = [x for x in first if x[0] in second_set] 

Suppose that at first it has m elements, and the second has n elements.

The sets are hashed, so their search is close to O (1), which gives the overall efficiency of O (m). Finding the second as a list is O (n), providing the overall efficiency of O (m * n).

+5
source

Perhaps you only want this instead of checking in :

 data = [x for x in first if 1 <= x[0] <= 5412 ] 
+1
source

All Articles