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

时间:2017-01-18 19:55:56

标签: python any

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

目前,我这样做:

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

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

5 个答案:

答案 0 :(得分:3)

您可以在条件生成器表达式上使用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.

答案 1 :(得分:2)

使用一个变量存储两种不同类型的信息不是一个好主意: 字符串是否匹配(// ... componentDidUpdate(prevProps, prevState) { if (prevProps !== this.props) { // re-render x <-- not sure how to do this } } )和是什么该字符串是(bool)。

您真的只需要第二条信息:虽然有一些创造性的方法可以在一个语句中执行此操作,但在上面的答案中,使用string循环确实有意义:

for

答案 2 :(得分:1)

我同意评论明确的循环是最清楚的。你可以捏造你原来的东西:

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

其中:

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

如果memoryisMatch,则全局True将包含匹配的字符串,或者如果isMatch为{{1},则保留其最初具有的任何值(如果有) }}

答案 3 :(得分:0)

假设您有a = ['a','b','c','d']b = ['x','y','d','z']

因此,通过执行any(i in b for i in a),您将获得True

您可以获得:

  • 匹配项数组:matches = list( (i in b for i in a) )
  • a中的第一个匹配项:posInA = matches.index(True)
  • 值:value = a[posInA]
  • b中的第一个匹配项:posInB = b.index(value)

要获取 all 个值及其索引,问题在于matches == [False, False, True, True]是多个值位于a还是b中,因此您需要在循环中(或在列表理解中)使用枚举。

for m,i in enumerate(a):
    print('considering '+i+' at pos '+str(m)+' in a')
    for n,j in enumerate(b):
        print('against '+j+' at pos '+str(n)+' in b')
        if i == j:
            print('in a: '+i+' at pos '+str(m)+', in b: '+j+' at pos '+str(n))

答案 4 :(得分:0)

对于 python 3.8 或更新版本,使用 Assignment Expressions

if any((match := string) in comment.body for string in myStringArray):
    print(match)