大家好,在python中有一个SQL stmt,其中包含测量值的输出。每个度量值都有一个唯一的id和时间戳。我现在的输出是这样的。 用于输出的Python代码:
arrayvals = []
for row in result:
arrayvals.append({
'request_ts': row[0],
'identifier': row[1],
'ts': row[2],
'value': row[5],
})
return (arrayvals)
输出:
{
"result_array": [
{
"identifier": "1",
"request_ts": "Mon, 22 Feb 2021 08:43:03 GMT",
"ts": "Wed, 17 Feb 2021 12:12:00 GMT",
"value": 17.1
},
{
"identifier": "1",
"request_ts": "Mon, 22 Feb 2021 08:43:03 GMT",
"ts": "Wed, 17 Feb 2021 12:12:00 GMT",
"value": 18.0
},
....
我想要的是,对于每个id,只有一个列表中的值输出。我曾尝试使用fetchall()重新实现这一点,但现在它获得了所有值的所有输出,如下所示: Pyton代码:
result2 = result.fetchall()
for row in result:
arrayvals.append({
'request_ts': row[0],
'identifier': row[1],
'ts': row[2],
'value': [i[5] for i in result2],
})
输出:
"result_array": [
{
"identifier": "01",
"request_ts": "Mon, 22 Feb 2021 08:46:48 GMT",
"ts": "Wed, 17 Feb 2021 12:12:00 GMT",
"value": [
17.1,
18.0,
2005.0,
17000.0,
1234.0
]
}
]
但我希望它是这样的:
"result_array": [
{
"identifier": "01",
"request_ts": "Mon, 22 Feb 2021 08:46:48 GMT",
"ts": "Wed, 17 Feb 2021 12:12:00 GMT",
"value": [
17.1,
18.0
]
}
{
"identifier": "02",
"request_ts": "Mon, 22 Feb 2021 08:46:48 GMT",
"ts": "Wed, 17 Feb 2021 12:12:00 GMT",
"value": [
2005.0,
17000.0,
1234.0
]
}
]
是否可以“组合”id以生成最后的输出? 差点忘了我的SQL是这样的:
SELECT
NOW() AS request_ts,
I.name AS identifier,
AI.ts,
AD.array_info_id,
AD.index,
AD.value AS measures
FROM
machine M
INNER JOIN identifier I
ON
I.machine_id = M.id
INNER JOIN PDA_ArrayInfo AI
ON
I.id = AI.identifier_id
INNER JOIN PDA_ArrayData AD
ON
AD.array_info_id = AI.id
WHERE
M.serial = :machine_serial_arg
根据马斯克林的回答:
for request_ts, identifier, ts, array_id, index, measures in result2.fetchall():
vals = vals_dict.get(array_id)
if vals is None:
# add record to index
values = vals_dict[array_id] = {
'request_ts': request_ts,
'identifier': identifier,
'ts': ts,
'value': [measures],
}
# adds the same record to the relust list
arrayvals.append(values)
else:
# look up the record in the index
vals['value'].append(measures)
return(values)
改变了两件事: “值”:[度量], VAL['value'].追加(度量值)
现在开始工作了,谢谢大家
最好的选择是首先修复sql语句以生成该语句。由于不显示SQL,因此很难在这方面提供帮助
第二个最佳选择是将数据存储为
identifier
到数据的映射,通过这种方式,您可以使用get
方法检查是否已经有此标识符的数据,如果没有,则创建一个新的,否则只需附加到现有的value
数组:第三个最好的选择,如果不可能的话,是。。。对列表执行相同的操作,如果列表中已经添加了id为的记录,请进行查找
如果列表中的条目数量可能很大,我仍然建议使用dict作为索引:在dict中查找记录是一个O(1)操作,在列表中是O(n),导致二次行为。如果你只有十几个条目,这不是一个问题;如果你有几千个条目,这是一个巨大的问题
相关问题 更多 >
编程相关推荐