If I have a list of strings strlst
and a list of regular expressions rexlst
, what is the most pythonic way to filter out every element of strlst
for which none of the regular expressions in rexlst
matches? So, as soon as one of the regular erpressions in rexlst
matches a string in strlst
, this particular string, should be included in the output list. The added complication* is, that I want **those elements of strlst
first that are matched by the first regex in rexlst, then those matched by the second and s.o.
A very simplified example:
import re
strlst = ['aaaaaa', '1234', 'bbbbb', '------', '.+/4-3', 'a1b2c3']
rexlst = [re.compile(x) for x in [r'^[a-z]+$', r'^d+$']]
Wanted result is the outputlist:
outlst = ['aaaaaa', 'bbbbb', '1234']
It should of cause work for arbitrary combinations of any strlst
and reglist
. A plus is a solution that is reasonably efficient and short.
The best I could come up with is:
outlist = filter(lambda x: any([True if r.match(x) else False for r in rexlst]), strlst)
But that gives the wrong order, namely it preserve the order of the strings as they appear in strlst
:
outlst = ['aaaaaa', '1234', 'bbbbb']
Aucun commentaire:
Enregistrer un commentaire