Search for the first instance of one list in the second list

I have two lists.

The first list is already sorted (by some other criteria) in such a way that the sooner the list is, the better.

sortedList = ['200', '050', '202', '203', '206', '205', '049', '047', '042', '041', '043', '044', '046', '045', '210', '211', '306', '302', '308', '309', '311', '310', '221', '220', '213', '212'] 

The second list is a list of valid values:

 allowedList = ['001','002','003','004','005','006','007','008','009','010','203','204','205','206','207','212','213','215','216'] 

I would like to select the highest sorted value that exists in allowList, and I only come up with silly ways to do this. Such things:

 import numpy as np temp = [] for x in allowedList: temp.append(sortedList.index(x)) np.min(temp) 

There must be a better way than that. Any ideas?

+6
source share
3 answers

Solutions using the fact that allowedlist already sorted are probably more efficient (and using set , they are certainly linear time and quadratic), but only for the sake of completeness your existing solution can be significantly shortened and excluded the temporary list:

 min(allowedList, key=sortedList.index) 

To do this, use the Python built-in min function , and not one of numpy - np.min , basically reuse them with numpy arrays; when using lists there is no need.

+2
source

Here you can do it without numpy

 >>> sorted_list = ['200', '050', '202', '203', '206', '205', '049', '047', '042', '041', '043', '044', '046', '045', '210', '211', '306', '302', '308', '309', '311', '310', '221', '220', '213', '212'] >>> allowed_list = ['001','002','003','004','005','006','007','008','009','010','203','204','205','206','207','212','213','215','216'] >>> allowed_set = set(allowed_list) >>> next((x for x in sorted_list if x in allowed_set), None) '203' 
+3
source
 allowedSet = set(allowedList) i, a = next(((i, a) for i, a in enumerate(sortedList) if a in allowedSet), (-1, None)) 

i is the index of the first such element (3), a is this element ('203').

If in any case the two lists do not have common elements, i = -1 and a = None , which you can change yourself.

0
source

Source: https://habr.com/ru/post/923536/


All Articles