Reputation: 41
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.
Upvotes: 3
Views: 1898
Reputation: 8301
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(" ","")
Upvotes: 4
Reputation: 26335
Nice and simple, here it is
a_list = ['56,78','72,67','55,66']
result = []
for coord in a_list:
result.append(tuple([int(x) for x in coord.split(',')]))
print(str(result).replace(" ", ""))
# Output
[(56,78),(72,67),(55,66)]
The first way I thought of was this:
a_list = ['56,78','72,67','55,66']
int_list = []
for coord in a_list:
for x in coord.split(','):
int_list.append(int(x))
result = []
for i in range(0, len(int_list), 2):
result.append((int_list[i], int_list[i+1]))
print(str(result).replace(" ", ""))
# Output
[(56,78),(72,67),(55,66)]
This way is also good if your new to python and want to solve this sort of problem with more procedure. My mindset for this was to just put all the coordinates into a list and group them into pairs at every second integer.
I hope this helps.
Upvotes: 1
Reputation: 78554
Use a list comprehension, split
the items and convert each subitem to int
using map
:
>>> result = [map(int, item.split(',')) for item in a_list ]
>>> result
[(56, 78), (72, 67), (55,66)]
On python 3.x, you should convert the map
object to a tuple
>>> result = [tuple(map(int, item.split(','))) for item in a_list ]
Upvotes: 1