【问题标题】:Check if the beginning of a string matches something from a list of strings (python)检查字符串的开头是否与字符串列表中的某些内容匹配(python)
【发布时间】:2014-04-04 01:50:11
【问题描述】:

我有一个字符串列表,我称之为过滤器。

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是否有办法做我所说的吗?仅从一个列表中获取以另一个列表中的内容开头的字符串?

【问题讨论】:

  • /Another/example_you_may_not_have_expected 怎么样?是否以/Another/example 开头?
  • 好收获。我将过滤器调整为“/Another/example/”

标签: python string list filtering


【解决方案1】:

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/ 路径不匹配。

【讨论】:

  • 只是出于好奇,这仍然是 O(n^2) 操作吗?
  • @warunsl:不,这是一个 O(nk) 操作; to_check 中有 n 个元素,filter 中有 k 个元素。
  • 哦,是的,我的意思是 O(nk)。谢谢。
  • @warunsl: 然而,str.startswith() 方法是在 C 中实现的(检查足够长,然后调用 memcmp),很难在纯 Python 中做出更有效的算法,打败它。
【解决方案2】:

使用正则表达式。

在下面试试

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/

【讨论】:

  • 字符串前缀匹配的正则表达式是多余的,尤其是当str.startswith() 接受一个元组时。你不能指望用 Python 中的 k 个元素循环来击败用 C 实现的 k 个元素的循环,尤其是添加字符串连接和函数调用的循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多