我的情况是我试图将字符串格式的元组数组转换为元组数组。
即。我想从:
['(-109.080842,45.002073)','(-105.91517,45.002073)','(-109.080842,45.002073)']
到
[(-109.080842,45.002073),(-105.91517,45.002073),(-109.080842,45.002073)]
这样做的目的是能够创建一个匀称的多边形。当元组是一个字符串时,它会抛出一个错误。从字符串到实际元组对象的最佳方法是什么?
答案 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)]