有没有办法获取字符串中匹配括号的索引?例如此示例:
text = 'aaaa(bb()()ccc)dd'
我想得到一个带有值的字典:
result = {4:14, 7:8, 9:10}
这意味着索引4和14上的括号匹配,7和8等等。非常感谢。
您的意思是自动方式?我不这么认为。
您需要使用stack创建一个程序,当您找到一个开放的括号时,您将在其中推入索引,而在找到一个封闭的括号时,将其弹出。
在Python中,您可以轻松地将列表用作堆栈,因为它们具有append()
和pop()
方法。
def find_parens(s):
toret = {}
pstack = []
for i, c in enumerate(s):
if c == '(':
pstack.append(i)
elif c == ')':
if len(pstack) == 0:
raise IndexError("No matching closing parens at: " + str(i))
toret[pstack.pop()] = i
if len(pstack) > 0:
raise IndexError("No matching opening parens at: " + str(pstack.pop()))
return toret
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句