【问题标题】:How to split coordinates in a string into a list of smaller lists如何将字符串中的坐标拆分为较小列表的列表
【发布时间】:2015-12-14 14:23:25
【问题描述】:

我正在尝试将一串坐标 "(x1, y1), (x2, y2)" 转换为 [[x1,y1], [x2,y2]] ,其中所有坐标也都转换为浮点数。

我当前的代码似乎没有修剪 y 坐标的空白,也没有将字符串转换为浮点数。

coordinates = "(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)"
for x in re.findall("\((.*?)\)", coordinates):
        final_coordinates = x.lstrip().split(',')

【问题讨论】:

    标签: python string python-3.x split


    【解决方案1】:

    一种选择可能是将coordinates 括在方括号中并使用literal_eval()

    >>> from ast import literal_eval
    >>> coordinates = "(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)"
    >>>
    >>> data = list(literal_eval(coordinates))
    >>> data
    [(-89.38477, 26.6671), (-89.38477, 27.13737), (-88.81348, 27.13737), (-88.81348, 26.6671)]
    

    【讨论】:

    • 不幸的是,这不起作用,我需要内括号也是方括号,我需要 POST 到端点的 json 的要求。
    • list(literal_eval(coordinates )) 怎么样?
    • @user4659009 好的,您可以按照 timgeb 的建议进行操作。或者,您可以将输入数据中的( 替换为[,并将) 替换为]
    猜你喜欢
    • 2019-01-20
    • 2012-11-04
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2022-11-17
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多