【发布时间】:2020-10-07 01:14:30
【问题描述】:
现在我有一个模式列表:
list1 = ['a[0-9]+', 'b[a-z]+', 'c[A-Z]+', ...]
我还有另一个字符串列表:
list2 = ['a1', 'babc', 'cABC', 'bbb', 'c1', ...]
我想快速知道list2中的字符串匹配list1中的哪个模式并返回它的索引(如果不匹配则返回-1):
output = [0, 1, 2, 1, -1, ...]
现在我只需使用“for”来实现这一点:
output = []
for string in list2:
matched = False
for pattern in list1:
if re.match(pattern, string):
output.append(list1.index(pattern))
matched = True
break
if not matched:
output.append(-1)
此方法有效,但由于 list1 和 list2 很大,因此需要的时间太长。那么有没有其他方法可以快速返回结果呢?
【问题讨论】:
标签: python python-3.x regex python-2.7