米贵网:个人网站,欢迎访问:

www.mindgui.com

#/usr/bin/env python
#-*- coding:utf-8 -*-

#思路:要先从最右边找‘(’;与之对应的‘)’要满足索引大于‘(’且最左边一个的索引;找到一个从‘)’的索引列表中去掉一个

#也可以通过a=str.find(')')找到右括号,然后使用b=str.rfind('(',a)找到与之对应的左括号

#以如下表达式为例
#1+3+((5*5+6)+5)-6/3-(4+5)
a='1+3+((5*5+6)+5)-6/3-(4+5)'
la=[]
lb=[]
for i in range(len(a)):
    if a[i]=='(':
        la.append(i)
    elif a[i]==')':
        lb.append(i)
if len(la)!=len(lb):
    print("Your expression are wrong with using symblic '('or ')'")
else:
    print("la:",sorted(la))
    print("lb:",sorted(lb))
    print("la|lb",set(la)|set(lb))
    couple1=dict.fromkeys(la,None)
    print(sorted(couple1.items(),key=lambda d :d[0],reverse=False))
    for i in sorted(couple1.keys(),reverse=True):
        for j in sorted(lb):
            if j>i:
                couple1[i]=j
                lb.remove(j)
                break
    print("括号分隔后的索引片段:",sorted(couple1.items(),key=lambda d:d[0]))

 

python实现括号分组

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-19
  • 2021-06-12
  • 2021-11-06
  • 2022-12-23
  • 2021-11-26
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 2022-12-23
  • 2021-05-25
  • 2021-04-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案