Python中匹配括号的索引

2024-05-18 10:08:07 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法得到字符串中匹配括号的索引?比如这个:

text = 'aaaa(bb()()ccc)dd'

我想买一本字典,里面有:

result = {4:14, 7:8, 9:10}

这意味着索引4和14上的圆括号是匹配的,7和8等等。 谢谢。


Tags: 字符串text字典resultdd括号cccbb
2条回答

检查平衡括号的标准方法是使用堆栈。在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

希望这有帮助。

相关问题 更多 >