【问题标题】:Coverting list of Coordinates to list of tuples将坐标列表转换为元组列表
【发布时间】:2016-09-26 16:33:40
【问题描述】:

我正在尝试将坐标列表转换为元组列表:

来自:

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

到:

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

我尝试过 for, in 循环将 a_list 中的每个元素转换为元组,但输出格式为:

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

对于我在这里做错的任何帮助将不胜感激。

编辑:修正了预期的输出,坐标和元组之间没有空格。

【问题讨论】:

    标签: python list for-loop tuples coordinates


    【解决方案1】:

    您可以使用列表推导:

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

    编辑:@Lol4t0 的较短版本

    如前所述,元素之间的空格来自打印列表。数据结构中没有实际的“空格”。但是,如果您希望打印没有任何空格的列表,您可以这样做:

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

    【讨论】:

    • 还是太长了:[tuple(map(int, e.split(','))) for e in a_list]
    • 打印列表时会自动设置空格。您可以打印您的预期输出列表list_of_tuples 以了解我的意思。它仍然会打印[(56, 78), (72, 67), (55, 66)]
    【解决方案2】:

    使用列表推导,split 项目并使用 map 将每个子项目转换为 int

    >>> result = [map(int, item.split(',')) for item in a_list ]
    >>> result
    [(56, 78), (72, 67), (55,66)]
    

    在 python 3.x 上,您应该将 map 对象转换为 tuple

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

    【讨论】:

    • 空格只是为了便于阅读。在这种情况下,它们没有任何意义。
    • 好的,谢谢。我们的讲师总是对空间感到压力,我猜他对我很敏感。
    【解决方案3】:

    又好又简单,就是这样

        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)]
    

    我想到的第一个方法是这样的:

        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)]
    

    如果您是 python 新手并希望通过更多程序来解决此类问题,这种方式也很好。我对此的想法是将所有坐标放入一个列表中,然后每隔一个整数将它们分组。

    我希望这会有所帮助。

    【讨论】:

    • @user6394303 我修改了最后一行以去掉空格。这对编辑正确吗?
    • 别担心,如果您喜欢这个答案,请为未来的用户点赞。
    • 我试过了,但还没有积累 15 个声望 :(
    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 2012-06-05
    • 1970-01-01
    • 2016-09-28
    • 2018-12-19
    • 2015-02-13
    • 2018-07-20
    相关资源
    最近更新 更多