Pet*_*bik 8 python parentheses
有没有办法在字符串中获取匹配括号的索引?例如这个:
text = 'aaaa(bb()()ccc)dd'
Run Code Online (Sandbox Code Playgroud)
我想要一本带有值的字典:
result = {4:14, 7:8, 9:10}
Run Code Online (Sandbox Code Playgroud)
这意味着索引4和14上的括号是匹配的,7和8是等等.非常感谢.
Bal*_*arq 12
你的意思是自动化的方式?我不这么认为.
您需要使用堆栈创建程序,在找到打开的括号时按下索引,并在找到右括号时弹出它.
在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
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
检查平衡括号的标准方法是使用堆栈.在Python中,这可以通过附加到标准列表并从中弹出来完成:
text = 'aaaa(bb()()ccc)dd'
istart = [] # stack of indices of opening parentheses
d = {}
for i, c in enumerate(text):
if c == '(':
istart.append(i)
if c == ')':
try:
d[istart.pop()] = i
except IndexError:
print('Too many closing parentheses')
if istart: # check if stack is empty afterwards
print('Too many opening parentheses')
print(d)
Run Code Online (Sandbox Code Playgroud)
结果:
In [58]: d
Out[58]: {4: 14, 7: 8, 9: 10}
Run Code Online (Sandbox Code Playgroud)