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

2024-10-01 09:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

目前,我是这样做的:

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

但是,不仅要知道isMatch是否为真,而且要知道{}的哪个元素有匹配项也是很有用的。有没有办法用我目前的方法做到这一点,或者我必须找到另一种方法来搜索匹配?在


Tags: 方法inapi元素forstringcommentany
3条回答

我同意这样的评论,即显式循环将是最清晰的。你可以这样敷衍你原来的样子:

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

其中:

^{pr2}$

如果isMatchTrue,则全局memory将包含匹配的字符串,或者如果{}是{},则保留它最初拥有的任何值(如果有)。在

使用一个变量来存储两种不同类型的信息不是一个好主意:一个字符串是否匹配(abool),以及这个字符串是什么(astring)。在

您实际上只需要第二条信息:虽然在一个语句中有创造性的方法来实现这一点,如上面的答案所示,使用for循环确实有意义:

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

if match:
    pass # do stuff

可以对条件生成器表达式使用^{}default=False一起使用:

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

如果没有匹配的项,则返回默认值(因此类似于any返回{}),否则返回第一个匹配项。在

这大致相当于:

^{pr2}$

或者,如果您希望isMatch和{}在不同的变量中:

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.

相关问题 更多 >