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

时间:2018-03-28 23:47:49

标签: python python-3.x tuples shapely

我的情况是我试图将字符串格式的元组数组转换为元组数组。

即。我想从:

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

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

这样做的目的是能够创建一个匀称的多边形。当元组是一个字符串时,它会抛出一个错误。从字符串到实际元组对象的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

他们是文字,所以你可以安全地评估它们:

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

答案 1 :(得分:0)

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