Skip to main content
 首页 » 编程设计

python之在干草堆中搜索几个等长的针(Python)

2025年05月04日37lautakyan007

我正在寻找一种在大字符串中搜索大量等长子字符串的方法。

我目前的方法基本上是这样的:

offset = 0 
found = [] 
 
while offset < len(haystack): 
  current_chunk = haystack[offset*8:offset*8+8] 
  if current_chunk in needles: 
     found.append(current_chunk) 
  offset += 1 

这太慢了。有更好的 Python 方法吗?

请您参考如下方法:

更多 Pythonic,更快:

for needle in needles: 
    if needle in haystack: 
        found.append(needle) 

编辑:这里是一些有限测试的测试结果

这个算法: 0.000135183334351

您的算法: 0.984048128128

快得多。