如何检查数组中的任何字符串是否存在于另一个字符串中?
像:
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"
该代码不起作用,它只是为了显示我想要实现的目标。
any()
True
如果您想要的只是or ,这是迄今为止最好的方法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))
一个令人惊讶的快速方法是使用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
所列),则此方法有效。如果是这样,指定为字符串会更简单:。a
a = 'abc'
您需要迭代 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"
在另一个字符串列表中查找多个字符串的一种紧凑方法是使用 set.intersection。这比大型集合或列表中的列表理解执行得快得多。
>>> astring = ['abc','def','ghi','jkl','mno']
>>> bstring = ['def', 'jkl']
>>> a_set = set(astring) # convert list to set
>>> b_set = set(bstring)
>>> matches = a_set.intersection(b_set)
>>> matches
{'def', 'jkl'}
>>> list(matches) # if you want a list instead of a set
['def', 'jkl']
>>>
jbernadas 已经提到了Aho-Corasick-Algorithm以降低复杂性。
这是在 Python 中使用它的一种方法:
从这里下载 aho_corasick.py
将它放在与你的主要 Python 文件相同的目录中并命名它aho_corasick.py
使用以下代码尝试算法:
from aho_corasick import aho_corasick #(string, keywords)
print(aho_corasick(string, ["keyword1", "keyword2"]))
请注意,搜索区分大小写
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"
只是有关如何获取 String 中可用的所有列表元素的更多信息
a = ['a', 'b', 'c']
str = "a123"
list(filter(lambda x: x in str, a))
还有另一种解决方案。使用set.intersection
. 对于单线。
subset = {"some" ,"words"}
text = "some words to be searched here"
if len(subset & set(text.split())) == len(subset):
print("All values present in text")
if subset & set(text.split()):
print("Atleast one values present in text")
这取决于上下文假设如果您想检查单个文字,例如(任何单个单词 a、e、w、..etc)就足够了
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")
我会使用这种功能来提高速度:
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)));