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

2024-05-13 13:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

{I要在包中找到这两个字符串。因此,只有strings中的第二个元素的结果应该是true,其余的应该是false。在

我想要的输出:

^{pr2}$

words不一定需要存储在list中,而且我知道{}也可以做类似的事情,但我更愿意使用其他方法而不是{},因为我的单词是汉语,需要使用一些复杂的regex而不是英语。在


Tags: and方法字符串falsetrue元素have单词
3条回答
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)

结果

假 是的 假

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

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

这将导致以下示例:

^{pr2}$

使用函数all()将是这里的最佳选择,但point是在不使用for循环的情况下执行。 下面是使用映射/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)

输出将是:

^{pr2}$

然而,幼稚的解决方案适合初学者:

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

相关问题 更多 >