簡體   English   中英

使用 catch 執行部分列表項匹配到另一個列表項

[英]Perform partial one list items match into another with a catch

我有兩個清單:

list_1 = ['world', 'abc', 'bcd', 'ghy', 'car', 'hell', 'rock']
list_2 = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']

我想檢查 list_1 的單詞是否以任何形狀或形式存在於 list_2 中,然后簡單地從 list_2 中刪除整個句子,最后打印 list_2

例如:

the word 'world' from list_1 should take out the sentence 'the world is big' from list_2
the word 'car' from list_2 should take out the sentence 'i want a car'

我試過使用這樣的列表理解,但遺憾的是它重復了

output = [j for i in list_1 for j in list_2 if i not in j]

您應該盡可能考慮為變量賦予有意義的名稱,這有助於您編寫代碼

你想要的是

  • 遍歷句子
  • 每次檢查list_1中沒有單詞
output = [sentence for sentence in list_2
          if all(word not in sentence for word in list_1)]

print(output)  # ['puppies are best']

您必須在條件表達式中使用單獨的列表推導。 在您的理解中,您正在為每個不在i中的j添加一個j for i in list_1 ,這就是為什么您會重復。

output = [j for j in list_2 if all([i not in j for i in list_1])]

您想檢查短語中是否出現任何單詞,因此any是 go 的方法。 在我看來,這比使用all並否定檢查更具可讀性。

words = ['world', 'abc', 'bcd', 'ghy', 'car', 'hell', 'rock']
phrases = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']

result = [phrase for phrase in phrases if not any(word in phrase for word in words)]
print(result)

你得到['puppies are best']


解決方案大致相當於:

result = []
for phrase in phrases:
    contains_any_word = False
    for word in words:
        if word in phrase:
            contains_any_word = True
            break
    if not contains_any_word:
        result.append(phrase)

使用set交集怎么樣?

list_1 = ['world', 'abc', 'bcd', 'ghy', 'car', 'hell', 'rock']
list_2 = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']

words = set(list_1)
output = [i for i in list_2 if not words & set(i.split())]
print(output)

Output:

['puppies are best']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM