np array 存储 json格式文件的写入与读取
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
Python中提供了list容器,可以当作数组使用。但列表中的元素可以是任何对象,因此列表中保存的是对象的指针,这样一来,为了保存一个简单的列表[1,2,3]。就需要三个指针和三个整数对象。对于数值运算来说,这种结构显然不够高效。
Python虽然也提供了array模块,但其只支持一维数组,不支持多维数组(在TensorFlow里面偏向于矩阵理解),也没有各种运算函数。因而不适合数值运算。
NumPy的出现弥补了这些不足。(——摘自张若愚的《Python科学计算》)
补: 第三方库joblibpython将numpy矩阵存储到本地
而经过测试无法直接通过json模块存入 例如array([2, 3, 4])
格式的数组,因此在存入json文件中的时候,我这里的思路是先通过 tolist()
模块将 np的array格式的数组转换成python自带的list,然后读取的时候再通过np.array()
处理后转回来
(注意这里处理时使用 tolist 会丢失指定的np数组中的类型如dtype=float64
这样的类型,而数值内部又都是整数,在使用np.array()
转回来的时候则会变成 int32,所以在重新从json文件中读取回来的时候,对于指定格式的数值,需要通过np.array()
指定加上对应丢失的类型,写法在读取代码的注释里面)
生成的 Distortion_correct.json 文件的内容
{"total": "[[2, 3, 4], [2.0, 3.0, 4.0], [[1.0, 2.0], [3.0, 4.0]], [[(1+0j), (2+0j)], [(3+0j), (4+0j)]]]"},
1.不同类型存入np多维数值至json文件中的示例代码
import numpy as np
import json
"""
[array([2, 3, 4]), array([2., 3., 4.]), array([[1., 2.],
[3., 4.]]), array([[1.+0.j, 2.+0.j],
[3.+0.j, 4.+0.j]])]
int32
float64
float64
complex128
"""
def save_setting_file(path, item):
# 先将字典对象转化为可写入文本的字符串
item = json.dumps(item)
try:
with open(path, "w", encoding='utf-8') as f:
f.write(item + ",\n")
print("保存"+path+"文件到本地完成")
except Exception as e:
print("json文件写入失败,请检查路径", e)
list_cs = []
## 常规创建方法
a = np.array([2,3,4])
b = np.array([2.0,3.0,4.0])
c = np.array([[1.0,2.0],[3.0,4.0]])
d = np.array([[1,2],[3,4]],dtype=complex) # 指定数据类型
print (a, a.dtype)
print (b, b.dtype)
print (c, c.dtype)
print (d, d.dtype)
print("...............................")
print("\n")
list_cs.append(a)
list_cs.append(b)
list_cs.append(c)
list_cs.append(d)
# print(list_cs)
# print("...............................")
# print(d)
# print("........................")
# print(list_cs[2])
print(".............准备打印储存 np 类型的数组列表.................")
print(list_cs)
print("\n")
tem_dict = {}
tem_list = []
# 通过 tolist() 将 array 类型的数值转换成,python自带的类型
for i in list_cs:
print(i.tolist())
tem_list.append(i.tolist())
print("---------------------------")
print(tem_list)
# 注意这里进行了类型转换,因为json.dumps 无法解析二维数值
tem_dict["total"] = str(tem_list)
print(tem_dict)
save_setting_file("Distortion_correct.json",tem_dict)
从json文件中读取多维数据的代码
import json
import numpy as np
"""
[array([2, 3, 4]), array([2., 3., 4.]), array([[1., 2.],
[3., 4.]]), array([[1.+0.j, 2.+0.j],
[3.+0.j, 4.+0.j]])]
"""
def set_setting_file(path):
try:
with open(path) as json_file:
setting_dict_string = json_file.readline()[:-2]
return json.loads(setting_dict_string)
except:
return {}
# 声明用于存储 np 二维数值的字典
finall_list = []
data_dict = set_setting_file("Distortion_correct.json")
print(data_dict)
print(type(data_dict))
print(type(data_dict["total"]))
data_list = eval(data_dict["total"])
print(type(data_list))
# 将读到的 list转换成 np格式的 多维数组
for i in data_list:
finall_list.append(np.array(i))
print("................................................-")
print(finall_list[0].dtype) # int32
print(finall_list[1].dtype) # float64
print(finall_list[2].dtype) # float64
print(finall_list[3].dtype) # complex128
# 指定对应np的数组类型的写法
# finall_list.append( np.array(data_list[3],dtype=complex) )
print("....................................")
print(finall_list)
2. 通过np.asarray的简单保存
保存
import numpy as np
import json
"""
[array([2, 3, 4]), array([2., 3., 4.]), array([[1., 2.],
[3., 4.]]), array([[1.+0.j, 2.+0.j],
[3.+0.j, 4.+0.j]])]
int32
float64
float64
complex128
"""
def save_setting_file(path, item):
# 先将字典对象转化为可写入文本的字符串
item = json.dumps(item)
try:
with open(path, "w", encoding='utf-8') as f:
f.write(item + ",\n")
print("保存"+path+"文件到本地完成")
except Exception as e:
print("json文件写入失败,请检查路径", e)
list_cs = []
## 常规创建方法
a = np.array([[2,3,4],[2,3,4],[22,334.4,4.45]])
list_cs.append(a)
print(".............准备打印储存 np 类型的数组列表.................")
print(list_cs)
print("\n")
tem_dict = {}
tem_list = []
# 通过 tolist() 将 array 类型的数值转换成,python自带的类型
for i in list_cs:
print(i.tolist())
tem_list.append(i.tolist())
print("---------------------------")
print(tem_list)
# 注意这里进行了类型转换,因为json.dumps 无法解析二维数值
tem_dict["total"] = str(tem_list)
print(tem_dict)
save_setting_file("2022_cs.json",tem_dict)
读取
import json
import numpy as np
"""
[array([2, 3, 4]), array([2., 3., 4.]), array([[1., 2.],
[3., 4.]]), array([[1.+0.j, 2.+0.j],
[3.+0.j, 4.+0.j]])]
"""
def set_setting_file(path):
try:
with open(path) as json_file:
setting_dict_string = json_file.readline()[:-2]
return json.loads(setting_dict_string)
except:
return {}
# 声明用于存储 np 二维数值的字典
finall_list = []
data_dict = set_setting_file("2022_cs.json")
print(data_dict)
print(type(data_dict))
print(type(data_dict["total"]))
data_list = eval(data_dict["total"])
print(data_list)
print(type(data_list))
# 将读到的 list转换成 np格式的 多维数组
finall_list = np.asarray(data_list)
# 指定对应np的数组类型的写法
# finall_list.append( np.array(data_list[3],dtype=complex) )
print("....................................")
print(type(finall_list))
print(finall_list)




适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6
binary -> binary_t
Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 22 天前
f3dc4684
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d)
---
updated-dependencies:
- dependency-name: github/codeql-action
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 28 天前
更多推荐
所有评论(0)