如果我有一个collection of strings
是否有一个数据结构或函数可以提高检查集合中的任何元素是否为主串中的substrings
?Python3快速的方法来查找如果集合中的任何元素是字符串的子串
现在我正在循环访问我的字符串数组并使用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) – Cripto
只是一个示例来演示'string'可能不包含'do_not_scan'的任何元素。我以前从未使用过地图,你会怎么做呢? – ClickThisNick
你想要'grep -l -Ff collections_of_strings main_string'的模拟吗?其中'collections_of_strings'文件包含字符串集合(每行一个),'main_string'文件包含主字符串(按原样)。 – jfs