Array of strings coordinates into array of integers in python

179
January 18, 2021, at 08:50 AM

I have an array of strings coordinates of the way:

A = [ '(0.0),(3,3),(5,8)', '(1,2),(5,8),(8,9),(20,6)' , '(45,6),(91,5),(86,4)' , '(100,2),(105,8),(53,6)']

I need to convert these into integers, so far i've tried to convert it by using int(A) or float(A).

By using int() i get this error:

"ValueError: invalid literal for int() with base 10: '(0, 0),(3, 0),(6, 0),(6, 5),(13, 0),(25, 5),(27, 5),(29, 5),(30, 0),(35, 5),(37, 5),(38, 5),(45, 0),(52, 0),(53, 5),(56, 0),(58, 0),(60, 0),(60, 5),(61, 5),(66, 0),(66, 5),(73, 0),(74, 0),(75, 5),(76"
Answer 1

As mentioned in my comment on the question, one way could be to use a safe eval method such as ast.literal_eval to parse the strings into tuples.

Assuming (0.0) should be (0,0):

import ast
[ast.literal_eval(i) for i in A]

Output:

[((0, 0), (3, 3), (5, 8)),
 ((1, 2), (5, 8), (8, 9), (20, 6)),
 ((45, 6), (91, 5), (86, 4)),
 ((100, 2), (105, 8), (53, 6))]
Answer 2

(Assuming 0.0 is a typo)

As suggested by S3DEV, a fast way to do it would be to use some type of eval(), but it's not recommended.

[list(eval(i)) for i in A]
[[(0, 0), (3, 3), (5, 8)],
 [(1, 2), (5, 8), (8, 9), (20, 6)],
 [(45, 6), (91, 5), (86, 4)],
 [(100, 2), (105, 8), (53, 6)]]

Comparison of eval vs literal_eval

  1. eval: This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Imagine using eval on rm -rf /!!

  2. ast.literal_eval: Only operates on a limited set of python literal structures. This makes if more secure.

In your case since your inputs are strings of coordinates (ensure this!) then both methods are equally safe/unsafe for you.

Answer 3

How about a regex solution? IMHO a bit cleaner, no need for using eval.

import re
A = ['(0,0),(3,3),(5,8)', '(1,2),(5,8),(8,9),(20,6)', '(45,6),(91,5),(86,4)', '(100,2),(105,8),(53,6)']
pattern = re.compile(r'\((\d+), *(\d+)\)')
[[(int(x), int(y)) for x, y in position] for position in [re.findall(pattern, group) for group in A]]
>> [[(0, 0), (3, 3), (5, 8)],
    [(1, 2), (5, 8), (8, 9), (20, 6)],
    [(45, 6), (91, 5), (86, 4)],
    [(100, 2), (105, 8), (53, 6)]]
READ ALSO
Select first row in each GROUP BY group?

Select first row in each GROUP BY group?

As the title suggests, I'd like to select the first row of each set of rows grouped with a GROUP BY

171
Code to Only Show Content With Specific URL

Code to Only Show Content With Specific URL

I'm using two shortcode sections in my "Account" page (one Woocommerce for past orders only) and then one shortcode section for MemberPress account detailsI want to only show the Woocommerce shortcode section when the URL is /my-account/orders/

132
Copy Button Preserving Line Breaks

Copy Button Preserving Line Breaks

I have some very basic Javascript that copies text upon the push of a buttonMy problem is that it doesnt preserve line breaks:

161