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
以外的其他方式,因为我的话是普通话汉语需要复杂使用正则表达式而不是英语。
答案 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))