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

问题描述 投票:1回答:1

我有我的输入字符串列表,我需要传递任何开括号的索引,并期望我的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不熟悉,感谢你抽出时间帮助我。谢谢!

python text-parsing
1个回答
0
投票

你只需要计算左支撑从起始线开始,当遇到左支撑时,增加​​它,当遇到右支撑时,减少它。当它再次达到零时,您会找到正确的索引。

您的示例代码:

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, '')

希望对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.