如何检查数组中的任何字符串是否存在于另一个字符串中?

例如:

a = ['a', 'b', 'c']
s = "a123"
if a in s:
    print("some of the strings found in s")
else:
    print("no strings found in s")

我如何替换如果a在s:行得到适当的结果?


当前回答

如果a或str中的字符串变长,您应该小心。简单的解决方案是O(S*(A^2)),其中S是str的长度,A是A中所有字符串长度的总和。要获得更快的解决方案,请查看用于字符串匹配的Aho-Corasick算法,该算法在线性时间O(S+A)内运行。

其他回答

为了提高速度,我会使用这样的函数:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False
a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"

python文档中推荐的regex模块支持这一点

words = {'he', 'or', 'low'}
p = regex.compile(r"\L<name>", name=words)
m = p.findall('helloworld')
print(m)

输出:

['he', 'low', 'or']

实现的一些细节:link

的元素上进行迭代。

a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:    
    if item in str:
        found_a_string = True

if found_a_string:
    print "found a match"
else:
    print "no match found"
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')