Python中匹配括号的索引
有没有办法获取字符串中匹配括号的索引?例如,对于这一个:Python中匹配括号的索引,python,parentheses,Python,Parentheses,有没有办法获取字符串中匹配括号的索引?例如,对于这一个: text = 'aaaa(bb()()ccc)dd' 我想买一本有值的字典: result = {4:14, 7:8, 9:10} 这意味着索引4和14上的括号是匹配的,7和8依此类推。 非常感谢。检查平衡支架的标准方法是使用堆栈。在Python中,这可以通过在标准列表中追加或弹出来完成: text = 'aaaa(bb()()ccc)dd' istart = [] # stack of indices of opening par
text = 'aaaa(bb()()ccc)dd'
我想买一本有值的字典:
result = {4:14, 7:8, 9:10}
这意味着索引4和14上的括号是匹配的,7和8依此类推。
非常感谢。检查平衡支架的标准方法是使用堆栈。在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)
结果:
In [58]: d
Out[58]: {4: 14, 7: 8, 9: 10}
你是说自动方式?
我不这么认为
您需要使用一个堆栈创建一个程序,在堆栈中,当您找到一个开括号时,您可以推送索引,当您找到一个闭括号时,可以弹出索引
在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
希望这有帮助。也试试这个
def match(str):
stack = []
ans = {}
for i,ch in enumerate(str):
if ch == "(":
stack.append(i)
else :
try:
if ch == ")":
ans[stack.pop()] = i
continue
except:
return False
if len(stack) > 0:
return False
else:
return ans
test_str = "()"
print(match(test_str))
很明显,有必要用Python编写简单的算法,因为你在5分钟内得到了三次几乎相同的答案。但是,这只捕获不平衡的开括号:太多的右括号将导致空列表中出现弹出框。感谢您的提示,现在答案更完整了。