是否可以使用列表元素和OR动态创建if语句?

0 投票
1 回答
3963 浏览
提问于 2025-04-18 17:01

我正在尝试把下面写的代码改成可以处理动态列表的形式,而不是现在这样只处理一个字符串:

required_word = "duck"
sentences = [["the", "quick", "brown", "fox", "jump", "over", "lazy", "dog"],
            ["Hello", "duck"]]

sentences_not_containing_required_words = []

for sentence in sentences:
   if required_word not in sentence:
      sentences_not_containing_required_words.append(sentence)

      print sentences_not_containing_required_words

举个例子,如果我有两个必需的单词(其实只需要其中一个),我可以这样做:

required_words = ["dog", "fox"]
sentences = [["the", "quick", "brown", "fox", "jump", "over", "lazy", "dog"],
            ["Hello", "duck"]]

sentences_not_containing_required_words = []

for sentence in sentences:
   if (required_words[0] not in sentence) or (required_words[1]not in sentence):
      sentences_not_containing_required_words.append(sentence)

      print sentences_not_containing_required_words
      >>> [['Hello', 'duck']]

但是,我需要的是有人能指导我如何处理一个大小会变化的列表(也就是列表里的项目数量会变),并且如果这个列表中的任何一个项目不在名为'sentence'的列表里,就能满足if语句的条件。不过,我对Python还很陌生,现在有点困惑,不知道该怎么更好地表达我的问题。我需要换个方法吗?

提前谢谢大家!

(注意,真正的代码会做一些比打印不包含必需单词的句子更复杂的事情。)

1 个回答

2

你可以很简单地用列表推导和any()这个内置函数来构建这个列表:

non_matches = [s for s in sentences if not any(w in s for w in required_words)]

这个代码会遍历列表sentences,同时创建一个新列表,只包含那些没有出现required_words中任何单词的句子。

如果你最终会有更长的句子列表,建议使用生成器表达式,这样可以减少内存的使用:

non_matches = (s for s in sentences if not any(w in s for w in required_words))

for s in non_matches:
    # do stuff

撰写回答