如何在Python中将字符串列表的类型更改为float
?
这是我的数据:
{"time":20180124,"data1m":"[[1516752000,11590.6,11616.9,11590.4,11616.9,0.25202387],[1516752060,11622.4,11651.7,11622.4,11644.6,1.03977764]]"}
此列表为每个元素分配索引,如:
a[0] = [, a[1] = [ and a[2] = 1,
我希望[1516752000,11590.6,11616.9,11590.4,11616.9,0.25202387]
存储在一个索引中,然后a[0][0] = 1516752000
,依此类推。
我该怎么做?
答案 0 :(得分:2)
可以使用json
模块解析此数据,如:
a = json.loads(data['data1m'])
data = {
"time": 20180124,
"data1m": "[[1516752000,11590.6,11616.9,11590.4,11616.9,0.25202387],"
"[1516752060,11622.4,11651.7,11622.4,11644.6,1.03977764]]"
}
import json
a = json.loads(data['data1m'])
print(a)
[
[1516752000, 11590.6, 11616.9, 11590.4, 11616.9, 0.25202387],
[1516752060, 11622.4, 11651.7, 11622.4, 11644.6, 1.03977764]
]
答案 1 :(得分:0)
您可以使用json
模块将data1m
的字符串值转换为列表列表,然后将子列表的元素转换为float
s像这样:
import json
from pprint import pprint
data = {"time":20180124,
"data1m":"[[1516752000,11590.6,11616.9,11590.4,11616.9,0.25202387],"
"[1516752060,11622.4,11651.7,11622.4,11644.6,1.03977764]]"}
a = json.loads(data["data1m"])
for index, row in enumerate(a):
a[index] = list(map(float, row))
pprint(a)
输出:
[[1516752000.0, 11590.6, 11616.9, 11590.4, 11616.9, 0.25202387],
[1516752060.0, 11622.4, 11651.7, 11622.4, 11644.6, 1.03977764]]