1

The problem: I have to convert a list of strings of tuples into a normal list of tuples. The reason is that I want to plot the (x,y) coordinates over an image.

I tried map,join, unzipping it, int(), float() but nothing seems to work. If I try the most logical way, using int() I get the following error:

ValueError: invalid literal for int() with base 10: '(50,144)'

This is my list of strings of tuples


vertices = ['(50,144)', '(242,144)', '(242,367)', '(50,367)']
type(vertices) >> list
type(vertices[0]) >> str

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Steve
  • 353
  • 3
  • 12

2 Answers2

3

Try with ast.literal_eval to safely parse the strings of tuples:

from ast import literal_eval

list(map(literal_eval, vertices))
# [(50, 144), (242, 144), (242, 367), (50, 367)]
yatu
  • 86,083
  • 12
  • 84
  • 139
1

A safe way would be parsing the strings yourself:

verts = [tuple(map(int, s[1:-1].split(','))) for s in vertices]

print(verts)
print(type(verts))
print(type(verts[0]))
print(type(verts[0][0]))

Output:

[(50, 144), (242, 144), (242, 367), (50, 367)]
<class 'list'>
<class 'tuple'>
<class 'int'>

You can also use eval but only if you are confident of the input's format (list of strings representing tuples of integers):

vertices = ['(50,144)', '(242,144)', '(242,367)', '(50,367)']

verts = [eval(s) for s in vertices]

print(type(verts))
print(type(verts[0]))
print(type(verts[0][0]))

Output:

[(50, 144), (242, 144), (242, 367), (50, 367)]
<class 'list'>
<class 'tuple'>
<class 'int'>
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55