神不在的星期二
你只需要从起始行开始计算左大括号,当遇到左大括号时,增加它,当遇到右大括号时,减少它。当它再次达到零时,您会找到正确的索引。示例代码:def get_closing_brace_index(str_list, left_idx): # input check, you can ignore it if you assure valid input if left_idx < 0 or left_idx >= len(str_list) or '(' not in str_list[left_idx]: return -1, '' # use a left brace counter left_count = 0 # just ignore everything before open_brace_index for i, s in enumerate(str_list[left_idx:]): for c in s: if c == '(': left_count += 1 elif c == ')': left_count -= 1 # find matched closing brace if left_count == 0: return i + left_idx, str_list[i + left_idx] # invalid brace match elif left_count < 0: return -1, '' return -1, ''def test(): mylist = [ 'a', 'b(', '(', 'cd', 'd(e)', 'hi)', 'last brace) ' ] print(get_closing_brace_index(mylist, 1)) # output (6, 'last brace) ') print(get_closing_brace_index(mylist, 2)) # output (5, 'hi)') print(get_closing_brace_index(mylist, 4)) # output (4, 'd(e)') print(get_closing_brace_index(mylist, 0)) # output (-1, '') print(get_closing_brace_index(mylist, 6)) # output (-1, '')希望能帮到你。