【发布时间】:2016-06-18 14:23:09
【问题描述】:
如果我有 collection of strings,是否有数据结构或函数可以提高检查集合的任何元素是否在我的主字符串上为 substrings 的速度?
现在我正在循环遍历我的字符串数组并使用in 运算符。有更快的方法吗?
import timing
## string match in first do_not_scan
## 0:00:00.029332
## string not in do_not_scan
## 0:00:00.035179
def check_if_substring():
for x in do_not_scan:
if x in string:
return True
return False
## string match in first do_not_scan
## 0:00:00.046530
## string not in do_not_scan
## 0:00:00.067439
def index_of():
for x in do_not_scan:
try:
string.index(x)
return True
except:
return False
## string match in first do_not_scan
## 0:00:00.047654
## string not in do_not_scan
## 0:00:00.070596
def find_def():
for x in do_not_scan:
if string.find(x) != -1:
return True
return False
string = '/usr/documents/apps/components/login'
do_not_scan = ['node_modules','bower_components']
for x in range(100000):
find_def()
index_of()
check_if_substring()
【问题讨论】:
-
有没有可能你在这里粘贴了错误的东西。或者
string = 'a'只是一个示例。因为node_modules永远不会在string中。话虽如此,您可以使用地图吗?其中键是do_not_scan的项目。那么搜索就是O(1) -
只是一个示例来演示
string可能不包含do_not_scan的任何元素。我以前从未使用过地图,你会怎么做呢? -
您想要
grep -l -Ff collections_of_strings main_string的模拟吗?其中collections_of_strings文件包含一组字符串(每行一个),main_string文件包含主字符串(原样)。 -
我将编辑,意味着是否有更好的数据结构,例如。将事物放在一组而不是数组中,这样可以加快搜索速度
标签: python algorithm python-3.x big-o string-algorithm