I have two lists.
The first list is already sorted (by some other criteria) such that the earlier in the list, 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 allowed 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 the allowedList, and I’m only coming up with silly ways of doing this. Things like this:
import numpy as np
temp = []
for x in allowedList:
temp.append(sortedList.index(x))
np.min(temp)
There has to be a better way than this. Any ideas?
The solutions using the fact that
allowedlistis already sorted are probably more efficient (and using aset, they certainly are – linear time vs quadratic), but for completeness only, your existing solution can be shortened a lot and the temporary list eliminated:This uses Python’s built-in
minfunction, rather than the one from numpy –np.minis mainly only useful if you’re using them with numpy arrays; there is no need for it when using lists.