如何检查多个子字符串是否一起出现在字符串中

时间:2017-04-28 09:18:08

标签: python list

strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']

我希望在列表strings中找到包含bird和bag的字符串,无论顺序如何。因此,仅strings中的第二个元素的结果应为真,其余元素应为假。

我想要的输出:

False
True
False

words不一定需要存储在列表中,我知道regex可以做类似的事情,但我更愿意使用除regex以外的其他方式,因为我的话是普通话汉语需要复杂使用正则表达式而不是英语。

5 个答案:

答案 0 :(得分:5)

列表理解将与all函数结合使用:

[all([k in s for k in words]) for s in strings]

这导致您的示例如下:

[False, True, False]

答案 1 :(得分:1)

strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']


for string in strings:
  stringlist = string.split()
  word1 , word2 = words
  if word1 in stringlist and word2 in stringlist:
    print(True)
  else:
    print(False)

<强>结果

假 真正 假

答案 2 :(得分:0)

就是这样:

for substring in strings:
    k = [ w for w in words if w in substring ]
    print (len(k) == len(words) )

答案 3 :(得分:0)

使用函数all()在这里是最好的选择,但点是没有for循环。 这是使用 map / lambda函数的解决方案。

strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
map(lambda x: all(map(lambda y:y in x.split(),words)),strings)

输出将是:

[False, True, False]

然而,天真的解决方案适合初学者:

for string in strings:
    count_match=0
    for word in words:
        if word in string.split():
            count_match+=1
    if(count_match==len(words)):
        print "True"
    else:
        print "False"

输出将是:

False
True
False

答案 4 :(得分:0)

对于可变数量的单词,不使用split函数。

strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']

 for string in strings:
    print(all(word in string for word in words))