如何从字符串中检索列表列表?

时间:2018-09-09 12:12:29

标签: python python-3.x

我有以下字符串mydata,它实际上是列表的嵌入式列表:

 u'[[[1.7594271439650333, 41.82815539277221], [1.7594360823099031,41.82815010753548], [1.7594365489105126,41.828102229437455], [1.75943006926896,41.82809815273617], [1.7593938715967752,41.8280981826361], [1.75938821767524, 41.828104309113314], [1.759388051589258, 41.8281507714983], [1.7594271439650333, 41.82815539277221]]]

我想将其转换为元组列表,如下所示:

mytuple = [tuple(l) for l in mydata[0]]

但是它不起作用,因为mydata确实是一个字符串。

1 个答案:

答案 0 :(得分:3)

由于该字符串是列表文字,因此可以从文档中使用ast.literal_eval

  

安全地评估表达式节点或Unicode或Latin-1编码   包含Python文字或容器显示的字符串。

import ast

a = u'[[[1.7594271439650333, 41.82815539277221], [1.7594360823099031, 41.82815010753548], [1.7594365489105126, 41.828102229437455], [1.75943006926896, 41.82809815273617], [1.7593938715967752, 41.8280981826361], [1.75938821767524, 41.828104309113314], [1.759388051589258, 41.8281507714983], [1.7594271439650333, 41.82815539277221]]]'
mydata = ast.literal_eval(a)
mytuple = [tuple(l) for l in mydata[0]]

print(mytuple)

输出

[(1.7594271439650333, 41.82815539277221), (1.7594360823099031, 41.82815010753548), (1.7594365489105126, 41.828102229437455), (1.75943006926896, 41.82809815273617), (1.7593938715967752, 41.8280981826361), (1.75938821767524, 41.828104309113314), (1.759388051589258, 41.8281507714983), (1.7594271439650333, 41.82815539277221)]