你可以在條件生成器表達式使用next
與default=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.
,或者如果你想有isMatch
和whatMatched
在不同的變量:
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.
只需刪除'any'並用顯式的'for'循環執行檢查。我在這裏沒有看到任何問題 –