Вопрос

I have got a list of strings that I am calling a filter.

filter = ["/This/is/an/example", "/Another/example"]

Now I want to grab only the strings from another list that start with one of these two (or more, the list will be dynamic). So suppose my list of strings to check is this.

to_check= ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]

When I run it through the filter, I would get a returned list of

["/This/is/an/example/of/what/I/mean", "/Another/example/this/is"]

Does anyone know if python has a way to do what I am talking about? Grabbing only the strings from a list that start with something from another list?

Это было полезно?

Решение

Make filter a tuple and use str.startswith(), it takes either one string or a tuple of strings to test for:

filter = tuple(filter)

[s for s in to_check if s.startswith(filter)]

Demo:

>>> filter = ("/This/is/an/example", "/Another/example")
>>> to_check = ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]
>>> [s for s in to_check if s.startswith(filter)]
['/This/is/an/example/of/what/I/mean', '/Another/example/this/is/']

Be careful, when prefix-matching with paths, you generally want to append trailing path separators so that /foo/bar doesn't match /foo/bar_and_more/ paths.

Другие советы

Using regular expression.

Try below

import re
filter = ["/This/is/an/example", "/Another/example"]
to_check= ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]

for item in filter:
    for item1 in to_check:
        if re.match("^"+item,item1):
             print item1
             break

Output

/This/is/an/example/of/what/I/mean
/Another/example/this/is/
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top