代码之家  ›  专栏  ›  技术社区  ›  Graviton

lambda函数中匹配括号字符的索引?

  •  0
  • Graviton  · 技术社区  · 7 年前

    s i 一、

    我应该注意,它只需要对括号起作用 () ,而不是 {} [] .

    例如

    >>> f( '(() foo ) bar' , 0)
    8
    

    f

    1 回复  |  直到 7 年前
        1
  •  4
  •   DSM    7 年前

    我懒得担心角落里的案子,但使用 itertools.accumulate

    f = lambda s,i: next((i for i,x in enumerate(accumulate
        ({'(': 1, ')': -1}.get(c,0) for c in s[i:]), i) if not x), None)
    
    In [31]: s = '(() foo ) bar'
    
    In [32]: f(s, 0)
    Out[32]: 8
    
    In [33]: f(s, 1)
    Out[33]: 2
    
    In [34]: f(s, 2)
    

    这通过跟踪字符串的高度来工作,计数(作为+1和)作为-1:

    In [36]: list(accumulate({'(': 1, ')': -1}.get(c,0) for c in s))
    Out[36]: [1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]