如何在any()中找到与Python匹配的内容?
我正在使用Python,使用like so查找如何在any()中找到与Python匹配的内容?,python,any,Python,Any,我正在使用Python,使用like so查找字符串[]数组和从Reddit的API中提取的注释之间的匹配 目前,我是这样做的: isMatch = any(string in comment.body for string in myStringArray) 但是,不仅要知道isMatch是否为真,还要知道mystringaray的哪个元素具有匹配项,这也是很有用的。用我目前的方法有没有办法做到这一点,或者我必须找到一种不同的方法来搜索匹配项 可以在条件生成器表达式上与default=F
字符串[]
数组和从Reddit的API中提取的注释之间的匹配
目前,我是这样做的:
isMatch = any(string in comment.body for string in myStringArray)
但是,不仅要知道isMatch
是否为真,还要知道mystringaray
的哪个元素具有匹配项,这也是很有用的。用我目前的方法有没有办法做到这一点,或者我必须找到一种不同的方法来搜索匹配项 可以在条件生成器表达式上与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.
我同意这样的评论,即显式循环是最清晰的。你可以这样捏造你的原创作品:
isMatch = any(string in comment.body and remember(string) for string in myStringArray)
^^^^^^^^^^^^^^^^^^^^^
其中:
def remember(x):
global memory
memory = x
return True
如果
isMatch
为True
,则全局内存将包含匹配的字符串,或者如果isMatch
为False
,使用一个变量存储两种不同类型的信息不是一个好主意:字符串是否匹配(abool
)以及该字符串是什么(astring
)
实际上,您只需要第二条信息:虽然在一条语句中有一些创造性的方法可以做到这一点,如上面的答案所示,但使用for
循环确实是有意义的:
match = ''
for string in myStringArray:
if string in comment.body:
match = string
break
if match:
pass # do stuff
假设你有a=['a','b','c','d']
和b=['x','y','d','z']
因此,通过执行any(b中的i代表a中的i)
可以得到True
你可以得到:
- 匹配数组:
matches=list((b中的i表示a中的i))
- 在
a
中,它首先匹配:posInA=matches.index(True)
- 值:
value=a[posInA]
- 在
b
中,它首先匹配:posInB=b.index(value)
要获取所有值及其索引,问题在于匹配==[False,False,True,True]
多个值是否在a
或b
中,因此需要在循环中使用enumerate(或在列表中)
用于python 3.8或更新版本
只需删除any
,并使用显式for
循环执行检查。我在这里没有看到任何问题。请看,在同一个变量中存储bool或匹配的字符串真的是一个好主意吗?这似乎让动态类型走得太远了。any
只要看一下就可以立即理解。afor
循环不会更糟。我已经研究了一分钟,仍然无法说服自己它是有效的;这使它成为一个糟糕的解决方案。@MarkRansom我包含了一个没有next
的版本,应该是等效的。以防它有助于理解发生了什么。:)在Python 3.8中,next不接受关键字参数,但默认值是一个位置参数。所以next((如果在websters中shizzle,则英语中shizzle代表shizzle),False)
我希望这是为了幽默地解决OP试图解决的问题:)Globals是邪恶的。如果你真的想使用这种技术,可以创建一个类对象,其中包含一个成员来记住匹配项。把它放到函数中,它就完美了。
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))
if any((match := string) in comment.body for string in myStringArray):
print(match)