user6394303 user6394303 - 6 months ago 14
Python Question

Coverting list of Coordinates to list of tuples

I'm trying to covert a list of coordinates to a list of tuples:

from:

a_list = ['56,78','72,67','55,66']


to:

list_of_tuples = [(56,78),(72,67),(55,66)]


I've tried doing a for, in loop to convert each element in a_list to a tuple however the output is in the form:

list_of_tuples = [('5', '6', '7', '8'), ('7', '2', '6', '7'), ('5', '5', '6', '6')]


Any help on what I am doing wrong here would be greatly appreciated.

EDIT: Fixed the expected output, no spaces between coordinates and tuples.

Answer

You can use list comprehension:

result = [tuple(map(int,element.split(','))) for element in a_list]

edit: shorter version by @Lol4t0

As mentioned the spaces between the elements come from printing the list. There are no actual "spaces" in the data structure. However, if you wish to print your list without any spaces you can do:

print str(result).replace(" ","")
Comments