我在python中有以下变量:
常量:
阵列
需要在以下视图中获取json:
{"data_list":[{"id":1,"time":"1","x":1,"y":1,"z":1}, {"id":1,"time":"2","x":2,"y":2,"z":2}]}
我已经完成了迭代。 什么是最快的方式?
答案 0 :(得分:1)
import json
d = {'id' : 1, 'time' : ['1', '2'], 'x' : ['1', '2'], 'y' : ['1', '2'], 'z' : ['1', '2']}
print(json.dumps({'data_list': [{'id' : d['id'], 'time' : t, 'x' : x, 'y' : y, 'z' : z} for t, x, y, z in zip(d['time'], d['x'], d['y'], d['z'])]}, indent=2))
会为您提供以下JSON输出:
{
"data_list": [
{
"id": 1,
"time": "1",
"x": "1",
"y": "1",
"z": "1"
},
{
"id": 1,
"time": "2",
"x": "2",
"y": "2",
"z": "2"
}
]
}
可替换地:
from operator import itemgetter
import json
d = {'id' : 1, 'time' : ['1', '2'], 'x' : ['1', '2'], 'y' : ['1', '2'], 'z' : ['1', '2']}
arr = ['time', 'x', 'y', 'z']
print(json.dumps({'data_list': [dict([('id', d['id'])] + list(zip(arr, v))) for v in zip(*itemgetter(*arr)(d))]}, indent=2))