Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

printstr(result).replace(" ","")

Solution 2:

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 ]

Solution 3:

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.

Post a Comment for "Coverting List Of Coordinates To List Of Tuples"