Nick_2440
Nick_2440

Reputation: 225

Python - Convert list of 2D co-ordinate pairs to 2 lists of X and Y components

I have a string which contains several pairs of 2D co-ordinate points as follows:

input = '(1, 2), (3, 5.5), (7, -2), (16, 0), (5, 3)'

I want to take this string and end up with two lists, named X and Y which contain the X and Y co-ordinates respectively of the points in the string (in their original order):

outputs:

X = ['1', '3', '7', '16', '5']

Y = ['2', '5.5', '-2', '0', '3']

How can I do this using Python 3?

Upvotes: 3

Views: 414

Answers (1)

user3483203
user3483203

Reputation: 51165

Use zip with ast.literal_eval

s = '(1, 2), (3, 5.5), (7, -2), (16, 0), (5, 3)'
x, y = zip(*ast.literal_eval(s))

x
(1, 3, 7, 16, 5)

y
(2, 5.5, -2, 0, 3)

If you are set on the output being a list, you can use:

x, y = map(list, zip(*ast.literal_eval(s)))

Upvotes: 7

Related Questions