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

时间:2014-08-12 15:57:58

标签: 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 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来说还是一个新手,我很难过,并且不知道如何更好地表达这个问题。我是否需要提出不同的方法?

提前致谢!

(请注意,真实代码会比打印sentences_not_containing_required_words更复杂。)

1 个答案:

答案 0 :(得分:1)

您可以使用列表推导和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