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

问题描述 投票:5回答:4

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

目前,我这样做:

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

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

python any
4个回答
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.

2
投票

使用一个变量存储两种不同类型的信息并不是一个好主意:字符串是否匹配(bool)和字符串是什么(string)。

你真的只需要第二条信息:虽然有一些创造性的方法可以在一个语句中完成,如上面的答案,使用for循环真的很有意义:

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

if match:
    pass # do stuff

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将包含匹配的字符串,或者如果isMatchFalse,则保留它最初具有的任何值(如果有的话)。


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)

要获取所有值及其索引,问题是matches == [False, False, True, True]多个值是否在ab中,因此您需要在循环中使用枚举(或在列表解析中)。

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))
© www.soinside.com 2019 - 2024. All rights reserved.