繁体   English   中英

使用Python中的嵌套列表推导过滤掉列表中的项目

[英]Filtering out items from a list using nested list comprehensions in Python

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

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

我正试图用列表推导来实现这一点。 例:

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

但是,它似乎没有工作,因为我得到一个错误告诉我在赋值之前使用了一个变量。

我一直试图寻找嵌套的理解,我确信这一定是被要求的,但我找不到任何东西。

我怎样才能做到这一点?

你的订单混乱了:

[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()函数来测试禁止的单词:

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

any()遍历生成器表达式,直到找到True值; 在句子中发现被禁词的那一刻,它就会停止工作。 这至少更有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM