如何用Python找到any()中匹配的内容?

Dan*_*y B 5 python any

我正在使用Python,使用any()这样来查找String[]数组和从Reddit的API中提取的注释之间的匹配.

目前,我这样做:

isMatch = any(string in comment.body for string in myStringArray)  
Run Code Online (Sandbox Code Playgroud)

但是,不仅知道它isMatch是否属实,而且它的哪个元素myStringArray具有匹配性也是有用的.有没有办法用我目前的方法做到这一点,还是我必须找到一种不同的方式来搜索匹配?

MSe*_*ert 11

您可以在条件生成器表达式上使用nextwith default=False

next((string for string in myStringArray if string in comment.body), default=False)
Run Code Online (Sandbox Code Playgroud)

当没有匹配项时返回默认值(所以就像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.
Run Code Online (Sandbox Code Playgroud)

或者,如果您想在不同的变量中使用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.
Run Code Online (Sandbox Code Playgroud)

  • 在 Python 3.8 中,next 不接受关键字参数,但默认是位置参数。所以 `next((shizzle for shizzle in English if shizzle in websters), False)` (2认同)

air*_*rne 10

对于 python 3.8 或更高版本,请使用赋值表达式

if any((match := candidate) in comment.body for candidate in candidates):
    print(match)
Run Code Online (Sandbox Code Playgroud)