【发布时间】:2016-01-04 16:51:37
【问题描述】:
from itertools import product
ttext = 'hello how are you?'
list1 = ['abra', 'hello', 'cfre']
list2 = ['dacc', 'ex', 'you', 'fboaf']
list3 = ['ihhio', 'oih', 'oihoihoo']
l = [list1, list2, list3]
所以我有上面的列表,我需要知道 ttext 中是否只有一个单词(只有一个)
我想要什么:例如,如果在 ttext 中我有“你好,我的名字是 brian”,它会说“好的,只有一个单词”,但如果我在 ttext 列表中有多个单词,那么“错误”。 ..
这里检查是否所有单词都在 ttext 中,我该如何检查所有列表中是否只有一个单词在 ttext 中
for words in product(*l):
print(words, all(word in ttext for word in words))
(('abra', 'dacc', 'ihhio'), False)
(('abra', 'dacc', 'oih'), False)
(('abra', 'dacc', 'oihoihoo'), False)
(('abra', 'ex', 'ihhio'), False)
(('abra', 'ex', 'oih'), False)
(('abra', 'ex', 'oihoihoo'), False)
(('abra', 'you', 'ihhio'), False)
(('abra', 'you', 'oih'), False)
(('abra', 'you', 'oihoihoo'), False)
(('abra', 'fboaf', 'ihhio'), False)
(('abra', 'fboaf', 'oih'), False)
(('abra', 'fboaf', 'oihoihoo'), False)
(('hello', 'dacc', 'ihhio'), False)
(('hello', 'dacc', 'oih'), False)
(('hello', 'dacc', 'oihoihoo'), False)
(('hello', 'ex', 'ihhio'), False)
(('hello', 'ex', 'oih'), False)
(('hello', 'ex', 'oihoihoo'), False)
(('hello', 'you', 'ihhio'), False)
(('hello', 'you', 'oih'), False)
(('hello', 'you', 'oihoihoo'), False)
(('hello', 'fboaf', 'ihhio'), False)
(('hello', 'fboaf', 'oih'), False)
(('hello', 'fboaf', 'oihoihoo'), False)
(('cfre', 'dacc', 'ihhio'), False)
(('cfre', 'dacc', 'oih'), False)
(('cfre', 'dacc', 'oihoihoo'), False)
(('cfre', 'ex', 'ihhio'), False)
(('cfre', 'ex', 'oih'), False)
(('cfre', 'ex', 'oihoihoo'), False)
(('cfre', 'you', 'ihhio'), False)
(('cfre', 'you', 'oih'), False)
(('cfre', 'you', 'oihoihoo'), False)
(('cfre', 'fboaf', 'ihhio'), False)
(('cfre', 'fboaf', 'oih'), False)
(('cfre', 'fboaf', 'oihoihoo'), False)
编辑: 如果列表中只有一个单词在 ttext 中:如果 ttext = 'hello my name is brian' then 'ok there's only one word 'hello' of the lists that is in ttext' 但如果我有“你好,你好吗”,我有“你好”和“你”,所以“列表中的两个单词在 ttext 中不行”
【问题讨论】:
-
您是否在询问是否至少有一个列表 (L),其中 ttext 包含不超过一个来自 L 的单词?或者您是在问是否有一个列表 (L),其中 ttext 恰好包含 L 中的一个单词?或者您是在问是否最多有一个列表 (L),其中 ttext 最多包含 L 中的一个单词?有很多可能的方法可以做到这一点,从你的问题中并不清楚你想要哪一种。
-
@ChadS.exactly 一个列表(L),其中 ttext 恰好包含 L 中的一个单词一个词我需要一个结果,如果在所有列表中只有一个元素在 ttext == ok (不是每个列表一个元素,对于所有检查的列表,我需要知道是否只有一个词在 ttext 中)
-
@mathieu,一些例子会有所帮助
-
@PadraicCunningham '你好,我的名字是 mathieu' 没问题,因为里面只有“你好”这个词(列表中有 1 个词)但是“你好,你好吗?”不行,因为列表中有两个词“你好”和“你”。
-
@mathieu,你想要一个字还是 1 个字或没有字?