Reputation: 5
Question about getting a string that matches condition & starting the new search from the location where the condition was met.
I have an ordered list of towns & I want to extract one string for each letter of the alphabet, each new search starts from the location of the previous search.
What is the best general approach? For the strings subsequent to 'A', do I need to compare the indices of the results or create a dictionary? e.g. In Python, can I continue the search from the specific location in the list?
# Ordered list of towns
towns = ['The Gord', 'Wilna Geo', 'The Framd', 'The Fild', 'Iron Geo', 'Brim Ness', 'RRH Saxa Vord', 'Houll', 'Skaw', 'Norwick', 'Burrafirth', 'Saxa Vord']
alpha = []
for elem in towns[:]:
if str(elem).startswith("A"):
alpha.append(elem)
break
# new search starting from position where 'A' was true; return next value starting with 'B' -
if str(elem).startswith("B"):
alpha.append(elem)
# Continue with the rest of the letters
return alpha
How would you conceptualise what I am trying to achieve?
Other than Python, what framework can better suit my needs, e.g. SQL, R, other?
Upvotes: 0
Views: 50
Reputation: 5907
I believe you can do something like this:
towns = ['The Gord', 'Wilna Geo', 'The Framd', 'The Fild', 'Iron Geo', 'Brim Ness', 'RRH Saxa Vord', 'Houll', 'Skaw', 'Norwick', 'Burrafirth', 'Saxa Vord']
alpha = []
current_letter = "A"
for elem in towns:
if elem[0] == current_letter:
alpha.append(elem)
current_letter = chr(ord(current_letter) + 1)
When an element if found to start with current_letter
, current_letter
changes to the next possible letter.
Note how I've changed the use of startswith
to [0]
(because we only check if elem
starts with one letter). I've also removed the unnecessary [:]
on towns. Finally, elem
works in place of str(elem)
(it's already a str
).
Upvotes: 1