Verifying that an item in a list starts with any of several prefixes in Python?

I am trying to check if any of the number of targets lines starts with one of the number of prefixes given, for example:

 prefixes = ["a", "b", "c"] targets = ["abar", "xbar"] 

then check if any targets element has a prefix that is in prefixes (and find those targets elements along with the first prefix that they matched). Here "abar" is the only element that fits. My own version:

 for t in target: if any(map(lambda x: t.startswith(x), prefixes)): print t 

Is there a better / shorter / faster way to use plain Python or numpy?

+4
source share
4 answers

If you want all matches to use only 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, use the following list comprehension code as a generator expression. This will be a short circuit if you just want to determine if there is any match.

 >>> nextmatch = next(((t,p) for t,p in product(targets,prefixes) if t.startswith(p)), None) >>> print(nextmatch) [('abar', 'a')] 
+2
source

same as @DSM

you can use a filter

 >>> prefixes = ("a", "b", "c") >>> targets = ["abar", "xbar"] >>> filter(lambda t: t.startswith(prefixes), targets) ['abar'] 
+2
source

I used lists as a result to store the prefix, as there could 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 empty lists

 >>> result = {k:v for k,v in result.items() if v} >>> result {'abar': ['a']} 
+1
source
0
source

All Articles