我正在尝试创建一个列表列表并将其添加到字典键中,然后将字典保存为 .mat
文件。我的代码如下所示:
from scipy.io import loadmat
dic = {"X": [[1,2,3],[1,2,4],[6,7,8,9],[1]]}
savemat('Test.mat', mdict=dic)
当我使用 loadmat
加载 .mat
文件并打印 dic['X']
;输出应为[[1,2,3],[1,2,4],[6,7,8,9],[1]]
。相反,我得到了这个:
[[array([[1, 2, 3]]) array([[1, 2, 4]]) array([[6, 7, 8, 9]]) array([[1]])]]
我的用于加载和恢复dic
的代码片段:
X = loadmat("Test.mat")
print(X['X'])
如何将原始列表存储到 .mat
文件中?
最佳答案
最可能的解释是您的库不能很好地处理列表列表,尤其是子列表具有不同长度的情况。您应该检查一下情况是否确实如此。
根据 docs , scipy.io.savemat
是为数组字典设计的,这不是您提供的:
Save a dictionary of names and arrays into a MATLAB-style .mat file.
This saves the array objects in the given dictionary to a MATLAB- style .mat file.
您可以做的是重组数据:
dic = {"A": np.array([1, 2, 3]),
"B": np.array([1, 2, 4]),
"C": np.array([6, 7, 8, 9]),
"D": np.array([1])}
请记住,具有不同长度的行的 numpy
数组将变成 dtype=Object
并且对于大多数矢量化函数来说几乎无法使用。它可能也无法与 scipy
很好地配合。
一个痛苦的解决方案是在再次加载数据时执行转换:
import numpy as np
from operator import itemgetter
lst = [[np.array([[1, 2, 3]]), np.array([[1, 2, 4]]),
np.array([[6, 7, 8, 9]]), np.array([[1]])]]
res = list(map(list, (map(itemgetter(0), map(list, lst[0])))))
[[1, 2, 3], [1, 2, 4], [6, 7, 8, 9], [1]]
<小时/>
Python 中没有原生函数组合,但可以使用第 3 方库 toolz
使上述逻辑更具可读性:
from operator import itemgetter
from toolz import compose
res = list(map(compose(list, itemgetter(0), list), lst[0]))
关于python - 带有列表列表的 Scipy.io savemat/loadmat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50075877/