我正在使用Python,使用any()这样来寻找String[]
数组和从Reddit的API中提取的注释之间的匹配。
目前,我这样做:
isMatch = any(string in comment.body for string in myStringArray)
但是,不仅知道isMatch
是否属实,而且myStringArray
的哪个元素与之匹配也是有用的。有没有办法用我目前的方法做到这一点,还是我必须找到一种不同的方式来搜索匹配?
你可以在条件生成器表达式上使用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.
使用一个变量存储两种不同类型的信息并不是一个好主意:字符串是否匹配(bool
)和字符串是什么(string
)。
你真的只需要第二条信息:虽然有一些创造性的方法可以在一个语句中完成,如上面的答案,使用for
循环真的很有意义:
match = ''
for string in myStringArray:
if string in comment.body:
match = string
break
if match:
pass # do stuff
我同意一个明确的循环最清楚的评论。你可以像这样捏造原件:
isMatch = any(string in comment.body and remember(string) for string in myStringArray)
^^^^^^^^^^^^^^^^^^^^^
哪里:
def remember(x):
global memory
memory = x
return True
然后,如果memory
是isMatch
,则全局True
将包含匹配的字符串,或者如果isMatch
是False
,则保留它最初具有的任何值(如果有的话)。
假设你有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]
多个值是否在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))