You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中带ID标识的数组列表JSON读写与还原技术问询

嘿,作为Python新手碰到numpy数组序列化的问题太正常了,我来一步步帮你搞定这个需求——给每个数组分配ID、存成JSON,之后再还原回原本的数组列表~

核心问题拆解

首先得明确:numpy的array对象是不能直接被JSON序列化的,所以第一步得把它们转成JSON支持的格式(比如普通列表),然后再处理ID分配和保存,最后读取时再转回numpy数组。

完整实现步骤

1. 导入依赖库

首先我们需要用到numpy和json模块:

import numpy as np
import json

2. 处理原始数组,分配ID并序列化

假设你的原始数据是:

some_list = [np.array([-12, 23]), np.array([-13, 22])]

我们可以用两种方式来存储带ID的数据:

方式一:用列表存储带ID的条目(更直观,保留顺序)

把每个数组转成列表,同时给它分配自增ID:

# 用enumerate生成自增ID,从1开始
data_with_ids = [
    {"id": idx + 1, "array": arr.tolist()} 
    for idx, arr in enumerate(some_list)
]
方式二:用ID作为键的字典(方便通过ID快速查找)

如果之后需要通过ID直接定位数组,这种方式更合适:

# ID转成字符串(因为JSON的键只能是字符串/数字,用字符串更稳妥)
data_dict = {
    str(idx + 1): arr.tolist() 
    for idx, arr in enumerate(some_list)
}

3. 保存为JSON文件

用json.dump()把数据写入文件,indent=4是为了让JSON文件更易读:

# 保存方式一的数据
with open("array_data.json", "w", encoding="utf-8") as f:
    json.dump(data_with_ids, f, indent=4)

# 保存方式二的数据
with open("array_data_dict.json", "w", encoding="utf-8") as f:
    json.dump(data_dict, f, indent=4)

4. 读取JSON并还原为原始数组列表

现在我们把保存的JSON读回来,再转成numpy数组:

还原方式一的数据
with open("array_data.json", "r", encoding="utf-8") as f:
    loaded_data = json.load(f)

# 还原成原始的numpy数组列表
restored_list = [np.array(item["array"]) for item in loaded_data]
# 如果需要保留ID和数组的映射
id_to_array = {item["id"]: np.array(item["array"]) for item in loaded_data}
还原方式二的数据
with open("array_data_dict.json", "r", encoding="utf-8") as f:
    loaded_dict = json.load(f)

# 按ID顺序还原成原始数组列表(假设ID是自增的)
restored_list_from_dict = [
    np.array(loaded_dict[str(i)]) 
    for i in range(1, len(loaded_dict) + 1)
]

额外小贴士

  • 如果需要全局唯一的ID(比如跨多个会话或项目),可以用uuid库生成:
    import uuid
    data_with_unique_ids = [
        {"id": str(uuid.uuid4()), "array": arr.tolist()} 
        for arr in some_list
    ]
    
  • 验证还原是否成功:可以用np.array_equal()来对比原始数组和还原后的数组,比如np.array_equal(some_list[0], restored_list[0])会返回True。

这样整个流程就完成啦,从分配ID、保存到还原,完美覆盖你的需求~

内容的提问来源于stack exchange,提问作者user7633957

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:22:20