I want to convert list of coordinates in string to tuple without using external library
type list
a = ['(1,4)', '(5,8)']
Output
type tuple
a = [(1,4), (5,8)]
what i did
a = tuple(a)
OUTPUT GETTING ('(1,4)', '(5,8)')
OUTPUT EXPECTED ((1,4), (5,8))
CodePudding user response:
There isn't a super clean way to do this in general. However, you can use ast.literal_eval
to convert individual elements to a tuple such as:
from ast import literal_eval
a = ['(1,2)', '(3,4)']
output_tuple = tuple(literal_eval(x) for x in a)
You can find the documentation for literal_eval
here.
CodePudding user response:
There you go
a = ['(1,4)', '(5,8)'] a = tuple([tuple(map(int, x[1:-1].split(','))) for x in a]) print(a)
CodePudding user response:
if you want to make it list like that and output with type tuple you have 2 method
method 1:
a = ['(1,4)', '(5,8)']
a = tuple([eval(x) for x in a])
print(a)
method 2: (using internal library)
from ast import literal_eval
a = ['(1,4)', '(5,8)']
a = tuple([literal_eval(x) for x in a])
print(a)