How to parse multiple times in python:
Method #1:
s = "(0 ,3) :5.0|(1 ,3) : -5.0"
def get_result(s: str) -> tuple:
goals = []
rewards = []
for pair in s.split("|"):
goal, reward = pair.split(":")
goals.append(eval(goal.strip()))
rewards.append(float(reward.strip()))
return (goals, rewards)
print(get_result(s))
Method #2:
txt = "(0 ,3) :5.0|(1 ,3) : -5.0"
txt = txt.replace(" ", "")
goal_states = []
their_rewards = []
for i in txt.split('|'): # ['(0,3):5.0', '(1,3):-5.0']
a, b = i.split(':')
_, n1, _, n2, _ = a # `a` is something like '(0,3)'
n1 = int(n1)
n2 = int(n2)
goal_states.append((n1, n2))
their_rewards.append(int(float(b)))
print(goal_states)
print(their_rewards)
OUTPUT:
[(0, 3), (1, 3)]
[5, -5]
Method #3:
import ast
s = "(0 ,3) :5.0|(1 ,3) : -5.0"
s = s.replace("|", ",")
ast.literal_eval(f"{{{s}}}")
OUTPUT:
{(0, 3): 5.0, (1, 3): -5.0}
Method #4:
string = "(0, 3): 5.0|(1 ,3) : -5-0"
parsed_list1, parsed_list2 = [i.split(":") for i in string.split("|")]
print(parsed_list1)
print(parsed_list2)
OUTPUT:
['(0, 3)', ' 5.0']
['(1 ,3) ', ' -5-0']
Method #5:
goal_states=[]
their_obstacles=[]
for i in "(0 ,3) :5.0|(1 ,3) : -5.0".split("|"):
goal_states.append(i.split(":")[])
their_obstacles.append(i.split(":")[1])