如何在Python中按content.system.id合并数组元素并保留时间戳顺序?
合并数组中相同
system.id的元素并按时间戳排序内容 需求:合并数组中具有相同["content"]["system.id"]的元素,合并时需整合时间戳(键)对应的内容,且需保持时间戳的顺序。示例中["content"]["system.id"]为123456789,时间戳顺序为1693217400000、1693217450000、1693217500000、1693217550000。
初始代码片段:
products = [] for item in data: products.append(item) ...
输入源
products = [ { "name":"aaa", "date":1693217443241, "content":{ "system.id":"123456789", "communication.id":"99", "message.id":"b0fa2", "1693217400000":{ "c1":"0", "c2":"0" }, "1693217500000":{ "c1":"0", "c2":"0" } } }, { "name":"aaa", "date":1693217443241, "content":{ "system.id":"000000001", "communication.id":"99", "message.id":"b0fa2", "1693217400000":{ "c1":"0", "c2":"0" }, "1693217500000":{ "c1":"0", "c2":"0" } } }, { "name":"aaa", "date":1693217443241, "content":{ "system.id":"123456789", "communication.id":"99", "message.id":"b0fa2", "1693217450000":{ "c1":"0", "c2":"1" }, "1693217550000":{ "c1":"0", "c2":"0" } } } ]
预期输出
products = [ { "name":"aaa", "date":1693217443241, "content":{ "system.id":"123456789", "communication.id":"99", "message.id":"b0fa2", "1693217400000":{ "c1":"0", "c2":"0" }, "1693217450000":{ "c1":"0", "c2":"1" }, "1693217500000":{ "c1":"0", "c2":"0" }, "1693217550000":{ "c1":"0", "c2":"0" } } }, { "name":"aaa", "date":1693217443241, "content":{ "system.id":"000000001", "communication.id":"99", "message.id":"b0fa2", "1693217400000":{ "c1":"0", "c2":"0" }, "1693217500000":{ "c1":"0", "c2":"0" } } } ]
解决方案代码
# 按system.id分组,合并时间戳内容 grouped = {} for item in products: system_id = item["content"]["system.id"] if system_id not in grouped: # 复制原项避免修改原始数据 grouped_item = item.copy() grouped_item["content"] = item["content"].copy() grouped[system_id] = grouped_item else: # 将当前项的时间戳内容合并到分组项中 for key, value in item["content"].items(): if key.isdigit(): grouped[system_id]["content"][key] = value # 对每个分组的时间戳键进行排序,整理成有序结构 merged_products = [] for item in grouped.values(): sorted_content = {} # 先添加非时间戳的固定字段 non_ts_keys = [k for k in item["content"] if not k.isdigit()] for k in non_ts_keys: sorted_content[k] = item["content"][k] # 按时间戳数值从小到大排序后添加 ts_keys = sorted([k for k in item["content"] if k.isdigit()], key=int) for k in ts_keys: sorted_content[k] = item["content"][k] item["content"] = sorted_content merged_products.append(item) # 输出合并后的结果 print(merged_products)
代码说明
- 使用字典
grouped以system.id为键对数组元素分组,相同id的元素会合并时间戳对应的内容 - 遍历过程中复制原元素,避免修改原始数据
- 最后对每个分组的
content字段进行整理:先保留固定字段,再将时间戳键按数值从小到大排序后添加,保证时间戳的顺序要求
内容的提问来源于stack exchange,提问作者Stéphane GRILLON
相关产品推荐
相关产品推荐

