如何将元组字符串的数组转换为元组的数组?

13 浏览
0 Comments

如何将元组字符串的数组转换为元组的数组?

这个问题已经有答案了

如何从字符串中解析元组?[重复]

我的情况是我正在尝试将一个字符串格式的元组数组转换为元组数组。

即:我想从:

['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']

[(-109.080842,45.002073),(-105.91517,45.002073),(-109.080842,45.002073)]

这样做的目的是能够创建一个弯曲的多边形。当元组是字符串类型时,会报错。从字符串转换成实际的元组对象的最佳方法是什么?

admin 更改状态以发布 2023年5月20日
0
0 Comments

这是使用 ast.literal_eval 函数的功能性方法:

from ast import literal_eval
lst = ['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']
res = list(map(literal_eval, lst))
# [(-109.080842, 45.002073), (-105.91517, 45.002073), (-109.080842, 45.002073)]

0
0 Comments

它们是字面量,所以你可以安全地计算它们:

>>> import ast
>>> L = ['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']
>>> [ast.literal_eval(x) for x in L]
[(-109.080842, 45.002073), (-105.91517, 45.002073), (-109.080842, 45.002073)]

0