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

例如:

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


当前回答

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)));

其他回答

你可以使用任何:

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。

一个惊人的快速方法是使用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', '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"

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

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

在另一个字符串列表中查找多个字符串的一种紧凑方法是使用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']
>>>