如果标题中的所有词:匹配(if allwords in title: match)

使用python3,我有一个单词列表,如: ['foot', 'stool', 'carpet']

这些列表的长度从1-6左右不等。 我需要检查成千上万的字符串,并且需要确保标题中包含所有三个单词。 其中: 'carpet stand upon the stool of foot balls.' 这是一个正确的匹配,因为所有的单词都在这里,即使它们出了故障。

我很想知道这件事,我唯一想到的是某种迭代,如:

for word in list: if word in title: match!

但这给我的结果就像'carpet cleaner'这是不正确的。 我觉得有一种快捷方式可以做到这一点,但我似乎无法使用过多的list(), continue, break或其他尚未熟悉的方法/术语来解决这个问题。 等等

Using python3, i have a list of words like: ['foot', 'stool', 'carpet']

these lists vary in length from 1-6 or so. i have thousands and thousands of strings to check, and it is required to make sure that all three words are present in a title. where: 'carpet stand upon the stool of foot balls.' is a correct match, as all the words are present here, even though they are out of order.

ive wondered about this for a long time, and the only thing i could think of was some sort of iteration like:

for word in list: if word in title: match!

but this give me results like 'carpet cleaner' which is incorrect. i feel as though there is some sort of shortcut to do this, but i cant seem to figure it out without using excessivelist(), continue, break or other methods/terminology that im not yet familiar with. etc etc.

最满意答案

你可以使用all() :

words = ['foot', 'stool', 'carpet'] title = "carpet stand upon the stool of foot balls." matches = all(word in title for word in words)

或者,反逻辑不是any()而not in :

matches = not any(word not in title for word in words)

You can use all():

words = ['foot', 'stool', 'carpet'] title = "carpet stand upon the stool of foot balls." matches = all(word in title for word in words)

Or, inverse the logic with not any() and not in:

matches = not any(word not in title for word in words)

更多推荐