528

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

像:

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"

该代码不起作用,它只是为了显示我想要实现的目标。

4

16 回答 16

1017

您可以使用any

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):

与检查是否找到列表中的所有字符串类似,请使用all代替any.

于 2010-08-02T16:15:25.513 回答
93

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)
于 2016-05-23T22:10:00.960 回答
53

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

于 2010-08-02T19:04:58.177 回答
32

只是为了增加一些多样性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))

于 2016-05-23T21:45:58.990 回答
16

一个令人惊讶的快速方法是使用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所列),则此方法有效。如果是这样,指定为字符串会更简单:。aa = 'abc'

于 2019-03-19T15:26:41.190 回答
14

您需要迭代 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"
于 2010-08-02T16:15:53.627 回答
5

在另一个字符串列表中查找多个字符串的一种紧凑方法是使用 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']
>>>
于 2021-01-12T04:27:50.287 回答
4

jbernadas 已经提到了Aho-Corasick-Algorithm以降低复杂性。

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

  1. 从这里下载 aho_corasick.py

  2. 将它放在与你的主要 Python 文件相同的目录中并命名它aho_corasick.py

  3. 使用以下代码尝试算法:

    from aho_corasick import aho_corasick #(string, keywords)
    
    print(aho_corasick(string, ["keyword1", "keyword2"]))
    

请注意,搜索区分大小写

于 2017-07-20T20:23:39.647 回答
3
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"
于 2010-08-02T16:16:40.673 回答
2

只是有关如何获取 String 中可用的所有列表元素的更多信息

a = ['a', 'b', 'c']
str = "a123" 
list(filter(lambda x:  x in str, a))
于 2018-06-25T13:51:48.883 回答
2

还有另一种解决方案。使用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")
于 2020-09-09T15:16:28.530 回答
2

python文档中推荐的正则表达式模块,支持这个

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

输出:

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

有关实施的一些细节:链接

于 2020-11-09T15:21:51.293 回答
1

这取决于上下文假设如果您想检查单个文字,例如(任何单个单词 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")
于 2016-11-30T05:17:45.867 回答
1
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')

输出示例图像

于 2017-11-26T23:58:28.173 回答
1

我会使用这种功能来提高速度:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False
于 2018-01-25T13:48:10.300 回答
0
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)));
于 2018-06-15T21:17:27.367 回答