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

例如:

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:行得到适当的结果?


当前回答

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

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False

其他回答

如果你想要的只是True或False, any()是目前为止最好的方法,但如果你想知道具体匹配哪个字符串/字符串,你可以使用一些东西。

如果你想要第一个匹配(默认为False):

match = next((x for x in a if x in str), False)

如果你想获得所有匹配项(包括重复项):

matches = [x for x in a if x in str]

如果你想获得所有非重复的匹配(不考虑顺序):

matches = {x for x in a if x in str}

如果你想按正确的顺序获得所有非重复的匹配项:

matches = []
for x in a:
    if x in str and x not in matches:
        matches.append(x)

这取决于上下文 假设你想检查单个文字(任何单个单词a,e,w,..等)就足够了

original_word ="hackerearcth"
for 'h' in original_word:
      print("YES")

如果你想检查original_word中的任何一个字符: 利用

if any(your_required in yourinput for your_required in original_word ):

如果您想要original_word中的所有输入,请使用所有输入 简单的

original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
    print("yes")
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']


# for each
for field in mandatory_fields:
    if field not in data:
        print("Error, missing req field {0}".format(field));

# still fine, multiple if statements
if ('firstName' not in data or 
    'lastName' not in data or
    'age' not in data):
    print("Error, missing a req field");

# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
    print("Error, missing fields {0}".format(", ".join(missing_fields)));

为了降低复杂度,jbernadas已经提到了aho - corasick -算法。

下面是在Python中使用它的一种方法:

从这里下载aho_corasick.py 将它放在与Python主文件相同的目录中,并将其命名为aho_corasick.py 用以下代码尝试该算法: 导入aho_corasick #(字符串,关键字) Print (aho_corasick(string, ["keyword1", "keyword2"]))

注意,搜索是区分大小写的

为了增加regex的多样性:

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

或者如果你的列表太长- any(re.findall(r'|'.join(a), str, re.IGNORECASE))