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

Python 是否可以使用列表元素和或动态创建if语句?,python,list,if-statement,Python,List,If Statement,我正在尝试修改我在下面编写的代码,使其能够处理所需值的动态列表,而不是字符串,因为它目前可以工作: required_word = "duck" sentences = [["the", "quick", "brown", "fox", "jump", "over", "lazy", "dog"], ["Hello", "duck"]] sentences_not_containing_required_words = [] for sentence in sente

我正在尝试修改我在下面编写的代码,使其能够处理所需值的动态列表,而不是字符串,因为它目前可以工作:

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']]
然而,我需要的是有人指导我处理一个大小(项目数量)不同的列表的方法,如果列表中的任何项目不在名为“句子”的列表中,则满足if语句。然而,由于我对Python非常陌生,我感到很困惑,不知道如何更好地表达这个问题。我需要想出一个不同的方法吗

提前谢谢


(请注意,真正的代码将执行比打印不包含必填词的句子更复杂的操作。)

通过列表理解和内置函数的组合,您可以非常轻松地构建此列表:

non_matches = [s for s in sentences if not any(w in s for w in 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

您可能需要
any
函数
any(w在句子中表示w在单词中)
。您也可以使用set intersection:
len(set(required_words)。intersection(句子))>0