Reputation: 949
Given a list such as:
lst = ['abc123a:01234', 'abcde123a:01234', ['gfh123a:01234', 'abc123a:01234']]
is there a way of quickly returning the index of all the items which start with a user-defined string, such as 'abc'
?
Currently I can only return perfect matches using:
print lst.index('abc123a:01234')
or by doing this in a number of steps by finding all the elements that start with 'abc' saving these to a new list and searching the original list for perfect matches against these.
If the only quick way is to use regex how could I still have the flexibility of a user being able to input what the match should be?
Upvotes: 3
Views: 1427
Reputation: 32189
You can accomplish that using the following script/method (which I admit is quite primitive):
lst = ['abc123a:01234', 'abcde123a:01234', ['gfh123a:01234', 'abc123a:01234']]
user_in = 'abc'
def get_ind(lst, searchterm, path=None, indices=None):
if indices is None:
indices = []
if path is None:
path = []
for index, value in enumerate(lst):
if isinstance(value, list):
get_ind(value, searchterm, path + [index], indices)
elif value.startswith(searchterm):
indices.append(path + [index])
return indices
new_lst = get_ind(lst, user_in)
>>> print new_lst
[[0], [1], [2, 1]]
Upvotes: 2