检查列表中是否存在至少一个字符串

时间:2020-02-19 12:43:57

标签: python

我有代码检查word_list中是否至少有一个情态动词。

with open('Requirements_good.txt') as myfile:
    word_list=[word for line in myfile for word in line.split()]


with open('Badwords_modalverbs.txt') as file:
    modalv = 0
    for word in file.readlines():
        if word.strip() in word_list:
            modalv = 1
    if modalv == 1:
        print ("one of the words found")

但是必须有一种更简单,更优雅的方法来解决此问题。最快的检查方法是什么?

又如何检查对立?:如果找不到任何单词,则打印任何内容

1 个答案:

答案 0 :(得分:8)

首先,将word_list设置为集合而不是列表,以便高效地测试其成员资格。然后,您可以使用any函数:

with open('Requirements_good.txt') as myfile:
    # set comprehension instead of list comprehension
    word_set = {word for line in myfile for word in line.split()}

with open('Badwords_modalverbs.txt') as file:
    if any(word.strip() in word_set for word in file):
        print("one of the words found")

这效率更高,因为您不再搜索列表来测试成员资格,而且any函数在找到一个匹配项后也不会继续搜索。 file.readlines()函数在这里也是不必要的; for word in file遍历各行,而无需先创建列表。

相关问题