Reputation:
I'm trying to check if any of a number of string targets
starts with one of any number of given prefixes
, e.g.:
prefixes = ["a", "b", "c"]
targets = ["abar", "xbar"]
then check if any element of targets
has a prefix that is in prefixes
(and find those elements of targets
along with the first prefix they matched). Here "abar"
is the only element that fits. My own version is:
for t in target:
if any(map(lambda x: t.startswith(x), prefixes)):
print t
is there a better/shorter/faster way using plain Python or numpy?
Upvotes: 4
Views: 2505
Reputation: 63749
If you want all the matches just use this list comprehension:
>>> from itertools import product
>>> matches = [(t,p) for t,p in product(targets,prefixes) if t.startswith(p)]
>>> print(matches)
[('abar', 'a'), ('cbar', 'c')]
If you just want the first one, use next with the list comprehension as a generator expression. This will short-circuit if you just want to determine if any match exists.
>>> nextmatch = next(((t,p) for t,p in product(targets,prefixes) if t.startswith(p)), None)
>>> print(nextmatch)
[('abar', 'a')]
Upvotes: 2
Reputation: 304355
I used lists in the result to store the prefix since there might be more than one match
>>> prefixes = ["a", "b", "c"]
>>> targets = ["abar", "xbar"]
>>> result = {t:[p for p in prefixes if t.startswith(p)] for t in targets}
>>> result
{'abar': ['a'], 'xbar': []}
If you need to filter the empty lists
>>> result = {k:v for k,v in result.items() if v}
>>> result
{'abar': ['a']}
Upvotes: 1
Reputation: 3073
same as @DSM
you can use filter
>>> prefixes = ("a", "b", "c")
>>> targets = ["abar", "xbar"]
>>> filter(lambda t: t.startswith(prefixes), targets)
['abar']
Upvotes: 2