Coverting list of Coordinates to list of tuples

强颜欢笑 提交于 2019-12-10 17:55:46

问题


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.


回答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:

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



回答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 ]



回答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.



来源:https://stackoverflow.com/questions/37498669/coverting-list-of-coordinates-to-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!