#### List comprehension to find matching parens

``````my_str = "hanz(and(franz/bob())+ 7) + tom(2)"
``````

``````[ i for i,c in enumerate(my_str) if c == '(']

# [4, 8, 18, 31]
``````

``````[ i for i,c in enumerate(my_str) if c == ')']

# [19, 20, 24, 33]
``````

``````[ ???? for i,c in enumerate(my_str) ???]

# [(4,24), (8,20), (18,19), (31,33)]
``````
2 个回复

``````my_str = "hanz(and(franz/bob())+ 7) + tom(2)"

pt_arr = [ 1 if c == '(' else -1 for i,c in enumerate(my_str ) if c == ')' or c == '(']
idx_arr = [ i for i,c in enumerate(my_str ) if c == ')' or c == '(']

[(idx_arr[strt_idx],idx_arr[strt_idx + [j for j,d in enumerate([ sum(pt_arr[strt_idx:i + 1]) for i,c in enumerate(pt_arr) if i >= strt_idx]) if d == 0][0]]) for strt_idx,f in enumerate(pt_arr) if f == 1]

# [(4,24), (8,20), (18,19), (31,33)]
``````

``````my_str = "hanz(and(franz/bob())+ 7) + tom(2)"
stack = []
parens = []
for i, c in enumerate(my_str):
if c == "(":
stack.append(i)
elif c == ")":
parens.append((stack.pop(), i))
print(parens) # [(18, 19), (8, 20), (4, 24), (31, 33)]
``````

``````stack = []
parens = [(stack.pop(), i) for i, c in enumerate(my_str)
if c == "(" and stack.append(i) or c == ")"]
print(parens) # [(18, 19), (8, 20), (4, 24), (31, 33)]
``````

2 使用字符串匹配优化列表理解

3 列表理解中的匹配、过滤和分组

4 匹配方案中的括号

2021-03-27 01:15:45 1 77   lisp
6 列表理解，获取匹配的嵌套项目[重复]

2015-12-04 07:10:14 1 196   python
7 修改RStudio“插入匹配的括号/引用”选项

2020-08-07 15:24:25 0 16   rstudio
8 使用列表推导找到合并的用户建议

2017-12-06 11:26:19 1 33   python