我有一个字符串列表,我称之为过滤器。
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"]
当我通过过滤器运行它时,我会得到一个返回的列表
["/This/is/an/example/of/what/I/mean", "/Another/example/this/is"]
有谁知道python是否有办法做我所说的?只从一个列表中抓取以另一个列表中的内容开头的字符串?
将filter
做成元组并使用str.startswith()
,需要一个字符串或一个字符串元组来测试:
filter = tuple(filter)
[s for s in to_check if s.startswith(filter)]
演示:
>>> 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/']
请注意,在与路径进行前缀匹配时,通常希望追加尾随路径分隔符,以便/foo/bar
与路径/foo/bar_and_more/
不匹配。
使用正则表达式。
在下面尝试
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
输出
/This/is/an/example/of/what/I/mean
/Another/example/this/is/