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?
To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).
How to Find the Index of a List Element in Python. You can use the index() method to find the index of the first element that matches with a given search object. The index() method returns the first occurrence of an element in the list. In the above example, it returns 1, as the first occurrence of “Bob” is at index 1.
Index in a list starts with 0. This essentially means that the first element in the list has an index of 0 and not 1 and subsequently the second element has an index of 1. This concept holds true for most programming languages.
Here's how you could do this 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'
The solutions using the fact that allowedlist
is already sorted are probably more efficient (and using a set
, they certainly are - linear time vs quadratic), but for completeness only, your existing solution can be shortened a lot and the temporary list eliminated:
min(allowedList, key=sortedList.index)
This uses Python's built-in min
function, rather than the one from numpy - np.min
is mainly only useful if you're using them with numpy arrays; there is no need for it when using lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With