I am trying to find certain string in a list that are between a lowerbound and upperbound (these are user input values). For example say I have a list, states = ['OH', 'NJ', 'NY', 'SD', 'NH', 'WI']. The user inputs lowerbound = 'NJ' and upperbound = 'SD'. I want the code to output ['OH', 'NJ', 'NY', 'SD'].
What I thought I could do is to separate each string into its own individual characters.
So for the user inputs I wrote this so that the ascii values of the input are added. Each character is added from the input in this case.
a = ord(lowerbound[0].lower()) ord(lowerbound[1].lower())
b = ord(upperbound[0].lower()) ord(upperbound[1].lower())
So then I tried this to retrieve the elements in a list that are between the user input. First it coverts all the elements in the list to their added ascii value. But it is not giving me the output I desire.
s_lst = []
lst = []
for s in states:
x = ord(s[0].lower()) ord(s[1].lower())
lst.append(x)
for i in lst:
if (b >= i >= a):
s_lst.append(i)
print(s_lst)
CodePudding user response:
Use a list comprehension to filter the list:
states = ['OH', 'NJ', 'NY', 'SD', 'NH', 'WI']
lowerbound = 'NJ'
upperbound = 'SD'
>>> [state for state in states if lowerbound<=state<=upperbound]
['OH', 'NJ', 'NY', 'SD']