Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串转换为2元组列表_Python_List_Python 3.x_Tuples - Fatal编程技术网

Python 将字符串转换为2元组列表

Python 将字符串转换为2元组列表,python,list,python-3.x,tuples,Python,List,Python 3.x,Tuples,我有这种形状的弦: d="M 997.14282,452.3622 877.54125,539.83678 757.38907,453.12006 802.7325,312.0516 950.90847,311.58322 Z" 它们是五角大楼的(x,y)坐标(第一个和最后一个字母是元数据,可以忽略)。我想要的是一个2元组列表,该列表将以浮点表示坐标,而不包含所有残差: d = [(997.14282, 452.3622), (877.54125, 539.83678), (757.38907

我有这种形状的弦:

d="M 997.14282,452.3622 877.54125,539.83678 757.38907,453.12006 802.7325,312.0516 950.90847,311.58322 Z"
它们是五角大楼的
(x,y)
坐标(第一个和最后一个字母是元数据,可以忽略)。我想要的是一个2元组列表,该列表将以浮点表示坐标,而不包含所有残差:

d = [(997.14282, 452.3622), (877.54125, 539.83678), (757.38907, 453.12006), (802.7325,312.0516), (950.90847, 311.58322)]
修剪绳子很容易:

>>> d.split()[1:-2]
['997.14282,452.3622', '877.54125,539.83678', '757.38907,453.12006', '802.7325,312.0516']
但是现在我想用一种简洁的方式创建元组。这显然不起作用:

>>> tuple('997.14282,452.3622')
('9', '9', '7', '.', '1', '4', '2', '8', '2', ',', '4', '5', '2', '.', '3', '6', '2', '2')
以原始字符串为例,我可以这样写:

def coordinates(d):
    list_of_coordinates = []
    d = d.split()[1:-2]
    for elem in d:
        l = elem.split(',')
        list_of_coordinates.append((float(l[0]), float(l[1])))
    return list_of_coordinates
哪种方法很好:

>>> coordinates("M 997.14282,452.3622 877.54125,539.83678 757.38907,453.12006 802.7325,312.0516 950.90847,311.58322 Z")
[(997.14282, 452.3622), (877.54125, 539.83678), (757.38907, 453.12006), (802.7325, 312.0516)]

然而,这个处理是一个更大的程序中一个小而琐碎的部分,我宁愿让它尽可能简短。有谁能告诉我一种不那么冗长的方法来将字符串转换成2元组列表吗

您可以使用列表理解在一行中完成此操作

x = [tuple(float(j) for j in i.split(",")) for i in d.split()[1:-2]]
这要经过
d.split()[1:-2]]
,每个应该分组在一起的对,用逗号将它们分开,将其中的每个项转换为一个浮点,并将它们分组在一个元组中


另外,您可能希望使用
d.split()[1:-1]
,因为使用
-2
会剪切最后一对坐标。

注意,不确定这是否是有意的-当您使用
d.split()[1:-2]
时,您将丢失最后一个坐标。假设这不是故意的,那么一行就可以了-

def coordinates1(d):
    return [tuple(map(float,coords.split(','))) for coords in d.split()[1:-1]]

如果丢失最后一个坐标是故意的,请在上面的代码中使用
[1:-2]

如果你做得好,可以使用列表理解或一些功能性内容(我的意思是“地图”)对其进行压缩:

当然,可以通过列表理解将其简化为一行,但可读性也会降低(而现在代码是硬读的)。虽然Guido讨厌函数式编程,但我发现这更符合逻辑。。。经过一些练习。祝你好运

    def coordinates(d):
        d = d[2:-2].split() # yeah, split here into pairs
        d = map(str.split, d, ","*len(d)) # another split, into tokens
        # here we'd multiplied string to get right size iterable
        return list(map(tuple, d)) # and last map with creating list
        # from "map object"