【问题标题】:Filtering out items from a list using nested list comprehensions in Python在 Python 中使用嵌套列表推导过滤掉列表中的项目
【发布时间】:2013-07-27 14:26:57
【问题描述】:

我有两个列表。一个包含句子,另一个包含单词。

我想要所有不包含单词列表中任何单词的句子。

我正在尝试通过列表推导来实现这一目标。示例:

cleared_sentences = [sentence for sentence in sentences if banned_word for word in words not in sentence]

但是,它似乎不起作用,因为我收到一条错误消息,告诉我在分配之前使用了一个变量。

我尝试寻找嵌套推导,我确信这一定是有人要求的,但我找不到任何东西。

我怎样才能做到这一点?

【问题讨论】:

    标签: python list python-2.7 list-comprehension


    【解决方案1】:

    你弄错了顺序:

    [sentence for sentence in sentences for word in words if banned_word not in sentence]
    

    这不会起作用,因为每次在句子中出现一个被禁止的词确实时都会列出sentence。看看完全扩展的嵌套循环版本:

    for sentence in sentences:
        for word in words:
            if banned_word not in sentence:
                result.append(sentence)
    

    改用any() function 来测试禁用词:

    [sentence for sentence in sentences if not any(banned_word in sentence for banned_word in words)]
    

    any() 仅在生成器表达式上循环,直到找到 True 值;一旦在句子中发现禁用词,它就会停止工作。至少这样更有效率。

    【讨论】:

    • 我尝试了列表理解(后者),但仍然出现错误。有没有可能需要......任何(在句子中禁止的单词为单词中的禁止单词)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2012-07-15
    • 2016-03-26
    • 1970-01-01
    • 2016-04-01
    • 2020-01-16
    相关资源
    最近更新 更多