我有一个单词列表,想知道下一个单词的位置或索引遵循某种模式(这是一个简单的例子,但正则表达式有点像魔鬼)
list = ["A","B","C","D","A","B","C","D","A","B","-","C","D"]
现在我找到了“A”的位置
a = [i for i,x in enumerate(list) if x == "A"]
但是,如果我想每次找到“A”时都找到“C”,然后递归地从下一个“A”重新开始。
我有一个单词列表,想知道下一个单词的位置或索引遵循某种模式(这是一个简单的例子,但正则表达式有点像魔鬼)
list = ["A","B","C","D","A","B","C","D","A","B","-","C","D"]
现在我找到了“A”的位置
a = [i for i,x in enumerate(list) if x == "A"]
但是,如果我想每次找到“A”时都找到“C”,然后递归地从下一个“A”重新开始。
list.index
有一个可选参数start
,您可以使用它来指定起始索引。
>>> lis = ["A","B","C","D","A","B","C","D","A","B","-","C","D"]
>>> for i,x in enumerate(lis):
... if x == 'A':
... print "next 'C' found at",lis.index('C',i)
...
next 'C' found at 2
next 'C' found at 6
next 'C' found at 11
更新:
>>> import re
>>> strs = "".join(lis)
>>> strs
'ABCDABCDAB-CD'
>>> r = re.compile(r'A[^C]+C')
>>> [m.end()-1 for m in r.finditer(strs)]
[2, 6, 11]
#or
>>> r = re.compile(r'A[^C]+')
>>> [m.end() for m in r.finditer(strs)]
[2, 6, 11]