[英]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.