【问题标题】:python code to get ending brace index from listpython代码从列表中获取结束大括号索引
【发布时间】:2019-03-29 07:38:53
【问题描述】:

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

输入列表:

mylist=[
'a',
'b(',
'(',
'cd',
'd(e)',
'hi)',
'last brace) '
]

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

getindex=func(mylist[2])

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

getindex=(5,'hi)')

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

【问题讨论】:

  • 请输入您的代码以便我们查看您的需求。
  • 你需要从重新思考你的函数设计开始。 mylist[2] 只是字符串"(",你的函数怎么知道起点的索引?您的列表中很容易有多个 "(" 元素。就此而言,它如何知道要在哪个列表中搜索?更好的“签名”是func(mylist, 2)。我会同意的。
  • 感谢您的回复。在我的文本文件中,我已经知道左大括号是单个字符是 '(' 并且我正在选择第一次出现的 '(' 并且没有其他字符。我可以通过任何一个 func(mylist[2])或 func(mylist, 2)

标签: python text-parsing


【解决方案1】:

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

为您提供示例代码:

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

希望对你有所帮助。

【讨论】:

  • 太棒了!。非常感谢recnac@。这行得通,我将尝试使用此代码并引发异常,以防它返回 -1。
  • 当一个测试用例中有两个((并且你需要在这种情况下找到索引时,这将失败
  • 维克似乎提到'我正在接受'(''@prashantrana的第一次出现
  • 最好使用队列来实现,从0开始找到所有开闭对索引,然后提供答案
  • 对于更复杂的问题,stack 是更好的解决方案,但它很简单,只需一个计数器即可处理,而且速度更快:) @prashantrana
猜你喜欢
  • 2013-03-30
  • 2020-04-15
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多