如何检查数组中的任何字符串是否存在于另一个字符串中?
喜欢:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
该代码不起作用,只是为了展示我想要实现的目标。
我会使用这种功能来提高速度:
def check_string(string, substring_list):
for substring in substring_list:
if substring in string:
return True
return False
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)));
关于如何在String中获取所有列表元素的更多信息
a = ['a', 'b', 'c']
str = "a123"
list(filter(lambda x: x in str, a))
一个令人惊讶的快速方法是使用set
:
a = ['a', 'b', 'c']
str = "a123"
if set(a) & set(str):
print("some of the strings found in str")
else:
print("no strings found in str")
如果a
不包含任何多字符值(在这种情况下使用any
列为above),则此方法有效。如果是这样,将a
指定为字符串更简单:a = 'abc'
。
any()
是迄今为止最好的方法,如果你想要的只是True
或False
,但如果你想知道哪些字符串/字符串匹配,你可以使用几个东西。
如果你想要第一场比赛(默认使用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
或str
中的字符串变长,你应该小心。直接的解决方案采用O(S *(A ^ 2)),其中S
是str
的长度,A是a
中所有字符串长度的总和。要获得更快的解决方案,请查看用于字符串匹配的Aho-Corasick算法,该算法以线性时间O(S + A)运行。
只是为了增加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))
你需要迭代a的元素。
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"
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"
jbernadas已经提到了Aho-Corasick-Algorithm以降低复杂性。
以下是在Python中使用它的一种方法:
aho_corasick.py
from aho_corasick import aho_corasick #(string, keywords)
print(aho_corasick(string, ["keyword1", "keyword2"]))
请注意,搜索区分大小写
这取决于上下文假设你想要检查单个文字(任何一个单词a,e,w,..等)就足够了
original_word ="hackerearcth"
for 'h' in original_word:
print("YES")
如果你想检查original_word中的任何一个字符:make use
if any(your_required in yourinput for your_required in 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")