簡體   English   中英

檢查字符串數組是否包含另一個字符串的 substring

[英]Check if an array of strings contains a substring of another string

假設我有一個字符串數組,以及其他一些句子,即。


fruits = ['apple', 'orange', 'grape']

example1 = 'John really enjoys melons'
example2 = 'John would like an apple'

如果“fruits”中的任何值是 text1 或 text2 的有效 substring,我想返回 True。

所以在這種情況下 text1 將是假的,而 text2 將是真的。 顯然,我可以遍歷 fruits 中的每個值,並為每個示例一個一個地檢查它是否存在於示例文本中。

但是,我的實際數據有數百個我想檢查的“示例”,而且我的“水果”數組要長得多。 在 Python 中是否有一種簡短/簡潔的方法來執行此操作? IE。 可以調用某種 function,而不必為每個示例遍歷“fruits”中的每個值。

您可以將any()與生成器表達式一起使用來遍歷所有fruits :(它會短路,因此一旦找到True ,它就會停止)

any(fruit in example1 for fruit in fruits) # True
any(fruit in example2 for fruit in fruits) # False

如果您只想以易於閱讀的方式編寫代碼,您可以嘗試設置交集 在內部,它必須通過每個示例字符串中的每個單詞 go 但使用集合可能會對其進行一些優化。

fruits = ['apple', 'orange', 'grape']
setFruits = set(fruits)

exampleList = ['John really enjoys melons', 'John really enjoys apple']

for example in exampleList:
    setExample = set(example.split(' '))
    if len(fruits.intersection(setExample)) > 0:
        print('True')
    else:
        print('False')

這可能有點快,因為您的示例字符串可以包含同一個單詞的多個副本,您不必一次又一次地檢查它們。

暫無
暫無

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

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