[英]Randomize strings from a list with constraints on string beginning python
[英]Check if the beginning of a string matches something from a list of strings (python)
我有一个称为过滤器的字符串列表。
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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.