Reputation: 41
I have a string of coordinates stored in a sequence of tuples such as '(522, 187) (522, 187) (522, 191) (523, 188) (522, 190)
(being stored in a deque first and then converted to string).
[(522, 187), (522, 187), (522, 191), (523, 188), (522, 190)]
?Simple splitting with split(',') doesn't work, as it then separates every coordinate due to ',' inside the tuple.
Upvotes: 2
Views: 1252
Reputation: 2821
Here is the answer, use regex.
res = [tuple(e.replace(" ", "").split(",")) for e in re.findall("[1-9]{3}, [1-9]{3}", string)]
This will be a list of tuples of strings. To convert them into ints
list(map(lambda x: (int(x[0]), int(x[1])), res))
Havent gone through the optimization of this code.
Upvotes: 1
Reputation: 917
This worked for me:
a = '(522, 187) (522, 187) (522, 191) (523, 188) (522, 190)'
res = list(eval(a.replace(', ',',').replace(' ',',')))
Output:
[(522, 187), (522, 187), (522, 191), (523, 188), (522, 190)]
Upvotes: 1
Reputation: 15364
You could do something like this:
from ast import literal_eval
tuples = '(522, 187) (522, 187) (522, 191) (523, 188) (522, 190)'
result = [literal_eval(f'({x})') for x in tuples.strip('()').split(') (')]
You can just memorize tuples = str(result)
next time! You can retrieve it with result = literal_eval(tuples)
Upvotes: 1
Reputation: 168913
You can split the string with ) (
, then massage the individual tuples:
>>> [tuple(int(v) for v in a.strip("()").split(", ")) for a in s.split(') (')]
[(522, 187), (522, 187), (522, 191), (523, 188), (522, 190)]
Secondly, there are many ways. One would be to just store all coordinates as a single string, with the implicit knowledge they are X/Y pairs: 522,187,522,187,522,191,...
Or you could store [(522, 187), (522, 187), (522, 191)]
directly and use ast.literal_eval()
to rehydrate it to a list-of-tuples.
Or, most preferably, you could use a data format that's not as stringly typed as CSV is, such as pickle files if you're working with Python alone, JSON if you need interchange, ...
Upvotes: 2