【发布时间】:2020-11-12 14:19:21
【问题描述】:
注意:我发现了一些类似的问题,但没有专门针对 Python 或此特定场景的问题。
这是一个小示例(工作)sn-p,它在较大的字符串中搜索字符串(从字符串数组中)。
#!/usr/bin/python
matches = [
"NEEDLE1",
"NEEDLE2",
"N33DL3"
]
haystack = 'this is a haystack, there may or may not be a noodley needle around here. Needless to say I hate N33DL3 people'
for match in matches:
if match in haystack:
print("Found")
问题:有没有一种“更好”的方法可以做到这一点,而不必遍历 (for match in matches) 每个数组元素?
编辑: 接受的答案有效并且速度很快。以下是时间:
# Ran the following:
starttime = timeit.default_timer()
for match in matches:
if match in haystack:
print("Found with looping in ", timeit.default_timer() - starttime)
starttime = timeit.default_timer()
if any(match in haystack for match in matches):
print("Found with any() in ", timeit.default_timer() - starttime)
starttime = timeit.default_timer()
if re.search('|'.join(matches), haystack):
print("Found with regex in ", timeit.default_timer() - starttime)
# After many trial runs, the regex continually came out much (much) faster:
('Found with looping in ', 9.5367431640625e-07)
('Found with any() in ', 5.0067901611328125e-06)
('Found with regex in ', 0.0003647804260253906)
【问题讨论】:
-
使用
any()函数。有很多 SO 问题说明了如何做到这一点。 -
any(match in haystack for match in matches) -
也可以将
matches转为正则表达式,然后检查正则表达式是否匹配。 -
@Barmar 谢谢,我会检查 any() 函数。