Transform string of coordinates stored in a tuple into list

Viewed 733

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).

  1. How is it possible to transform this entity into a list/deque of tuples? So that it would look like [(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.

  1. Is there any more convenient way of storing a list/deque of tuples in a single cell of .csv file? I need to store all coordinates received from every trial in an individual cell. Making two columns with _x and _y coordinates sometimes results into unequal length of these arrays.
4 Answers

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, ...

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.

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)

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)]
Related