So I was doing a PEMDAS calculator and I managed to do everything but the parenthesis so my question is how to extract from a list like this :
r = ["4"," ","2","(","2"," ","5",")"]
["2"," ","5"]
and to clarify it more if the code was like this:
r = ["4"," ","2","(","2"," ","5",")"," ","(","2"," ","5",")"]
this should be the output ["2"," ","5","2"," ","5"]
CodePudding user response:
you can use this code to extract data between parenthesis. so you have a list which contain the data you want.
r = ["4"," ","2","(","2"," ","5",")"]
r_new = []
for i in range(len(r)):
if r[i] == "(":
i=i 1
for j in range(len(r)-i):
if(r[i j]==")"):
print(r_new)
break
else:
r_new.append(r[i j])
CodePudding user response:
Will this be workable for you?
r = ['4', ' ', '2', '(', '2', ' ', '5', ')', ' ', '(', '2', ' ', '5', ')']
index = [x for x,y in enumerate(r) if y == '(' or y == ')']
grouped_index = [[index[i*2],index[i*2 1]] for i in range(int(len(index)/2))]
grouped_value = [r[i[0] 1:i[1]] for i in grouped_index]
sum(grouped_value, [])
['2', ' ', '5', '2', ' ', '5']