简体   繁体   中英

how to convert coordinate string list to tuple type in python

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

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.

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)

There you go

a = ['(1,4)', '(5,8)']
a = tuple([tuple(map(int, x[1:-1].split(','))) for x in a])

print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM