2017-01-18 35 views
2

我正在Python中工作,使用any()這樣來尋找String[]數組與從Reddit的API中提取的評論之間的匹配。如何在Python中找到與any匹配的內容?

目前,我正在做這樣的:

isMatch = any(string in comment.body for string in myStringArray) 

但是,這也將是有益的不只是知道isMatch是真實的,但它是其中的myStringArray元素進行了比賽。有沒有辦法用我目前的方法來做到這一點,還是我必須找到一種不同的方式來搜索比賽?

+4

只需刪除'any'並用顯式的'for'循環執行檢查。我在這裏沒有看到任何問題 –

回答

1

你可以在條件生成器表達式使用nextdefault=False

next((string for string in myStringArray if string in comment.body), default=False) 

時,有沒有項目匹配則返回默認的(所以它就像any返回False),否則返回第一個匹配項。

這大致相當於:

isMatch = False # variable to store the result 
for string in myStringArray: 
    if string in comment.body: 
     isMatch = string 
     break # after the first occurrence stop the for-loop. 

,或者如果你想有isMatchwhatMatched在不同的變量:

isMatch = False # variable to store the any result 
whatMatched = '' # variable to store the first match 
for string in myStringArray: 
    if string in comment.body: 
     isMatch = True 
     whatMatched = string 
     break # after the first occurrence stop the for-loop. 
+0

將* bool或匹配的字符串存儲在同一個變量中真的是一個好主意嗎?這似乎正在採取動態類型的方式。 – brianpck

+1

只要看着它,立即就能理解「任何」。一個'for'循環不會更糟糕。我一直在看這一分鐘,仍然無法說服自己,它的工作原理;這使得它不好解決。 –

+0

@MarkRansom我已經包含了一個沒有'next'的版本,它應該是等價的。以防萬一它有助於理解發生了什麼。 :) – MSeifert

0

我的意見,即外在的循環將是最明顯的同意。您可以做傻事你原來像這樣:

isMatch = any(string in comment.body and remember(string) for string in myStringArray) 
            ^^^^^^^^^^^^^^^^^^^^^ 

其中:

def remember(x): 
    global memory 
    memory = x 
    return True 

那麼全球memory將包含匹配的字符串,如果isMatchTrue,或原本保留的任何值(如果有的話),它如果isMatchFalse

+3

我希望這是幽默地爲OP正試圖解決的問題:) – brianpck

+0

Globals是邪惡的。如果你真的想使用這種技術,用成員創建一個類對象來記住匹配。 –

2

這不是使用一個變量來存儲兩種不同的信息是個好主意:是否字符串匹配(一bool)和這個字符串就是(一string)。

你真的只需要在第二條信息:同時有創造性的方式來做到這一點的一個聲明,因爲在上面的回答,真的很有意義使用for循環:

match = '' 
for string in myStringArray: 
    if string in comment.body: 
     match = string 
     break 

if match: 
    pass # do stuff 
+0

把它放到一個函數中,它是完美的。 –

相關問題