python代码从列表中获取结束大括号索引

我有我的字符串输入列表,我需要在其中传递任何左大括号的索引,并期望我的 python 函数返回其相应的右大括号的索引及其值。


输入列表:


mylist=[

'a',

'b(',

'(',

'cd',

'd(e)',

'hi)',

'last brace) '

]

我需要获取列表的索引和字符串


getindex=func(mylist[2])

getindex 应该有hi)索引 5。它应该忽略 ex:d(e)或last brace)等之间的任何相应的平衡大括号。


getindex=(5,'hi)')

我对 python 不太熟悉,感谢您帮助我的时间。谢谢!


慕森王
浏览 175回答 1
1回答

神不在的星期二

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

相关分类

Python