一、保存、读取字典
1. 保存字典
import numpy as np
dictionary = {
'a': [1, 2, 3],
'b': [10, 20, 30],
'c': [100, 200, 300],
}
np.save("dictionary.npy", dictionary)
2. 读取字典
import numpy as np
dictionary = np.load("dictionary.npy", allow_pickle=True).item()
print(dictionary)
print(type(dictionary))
运行结果:
{'a': [1, 2, 3], 'b': [10, 20, 30], 'c': [100, 200, 300]}
<class 'dict'>
二、保存、读取list
1. 保存list
import numpy as np
data_list = [1, 2, 3, 4, 5]
np.save("data_list.npy", data_list)
2. 读取list
import numpy as np
data_list = np.load("data_list.npy", allow_pickle=True)
print(data_list)
print(type(data_list))
运行结果:
[1 2 3 4 5]
<class 'numpy.ndarray'>
可以发现,list被转化为ndarray了,要想将ndarray转为list,则:
import numpy as np
data_list = np.load("data_list.npy", allow_pickle=True).tolist()
print(data_list)
print(type(data_list))
运行结果:
[1, 2, 3, 4, 5]
<class 'list'>
完。