2017-08-16 66 views
0

我可以用它來確定是否有任何一組多個字符串的另一個字符串存在,蟒蛇 - 多串找到多個字符串

bar = 'this is a test string' 
if any(s in bar for s in ('this', 'test', 'bob')): 
    print("found") 

,但我不知道如何檢查是否有在多個字符串中的任意一個字符串中都會出現。這似乎是可行的。在語法上它並沒有失敗,但它不會是打印我出什麼:

a = 'test string' 
b = 'I am a cat' 
c = 'Washington' 
if any(s in (a,b,c) for s in ('this', 'test', 'cat')): 
    print("found") 

回答

1

需要通過測試串的元組進行迭代:

a = 'test string' 
b = 'I am a cat' 
c = 'Washington' 
if any(s in test for test in (a,b,c) for s in ('this', 'test', 'cat')): 
    print("found") 
+0

啊好 - 這是有道理的。謝謝! –

1

你可以試試這個:

a = 'test string' 
b = 'I am a cat' 
c = 'Washington' 

l = [a, b, c] 

tests = ('this', 'test', 'cat') 

if any(any(i in b for b in l) for i in tests): 
    print("found") 
+0

這實際上非常乾淨,而我的真實數據集要大得多 - 這可能會使事情變得更容易閱讀。謝謝! –

+0

@BrianPowell很高興能幫到你! – Ajax1234

2

在這一點上,可能值得編譯一個你正在尋找的子串的正則表達式,然後用一個單一的檢查來使用它......這意味着你只掃描每個字符串一次 - 不是潛在的最少三次(或者你要找的很多子串),並且保持在一個單一的理解水平上進行檢查。

import re 

has_substring = re.compile('this|test|cat').search 
if any(has_substring(text) for text in (a,b,c)): 
    # do something 

注意您可以修改表達式爲僅搜索全字,如:

has_word = re.compile(r'\b(this|test|cat)\b').search 
+0

我感謝您花時間回答我已經接受答案的問題。這是一個好主意,在我檢查50個字符串的情況下,它應該使事情變得更快更高效,所以謝謝! –