【问题标题】:Check for existence of at least one string in a list检查列表中是否存在至少一个字符串
【发布时间】:2020-02-19 12:43:57
【问题描述】:

我的代码可以检查我的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")

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

如何检查相反的词?:如果没有找到任何单词,则打印任何内容

【问题讨论】:

标签: python


【解决方案1】:

首先,将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 遍历行而不首先创建列表。

【讨论】:

  • 如果我想检查对立面,我应该怎么做? - 如果没有找到任何单词,打印某事?
  • if not any(...):
猜你喜欢
  • 2022-08-19
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2023-02-23
相关资源
最近更新 更多