python - 在 python 中从文本文件中读取多个变量的聪明方法

标签 python numpy

我正在尝试加载存储在单个文本文件中的多个向量和矩阵(对于 numpy)。 该文件如下所示:

%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7

理想的解决方案是拥有一个像这样的字典对象:

{'VectorB': [3, 4, 5, 6, 7], 'VectorA': [1, 2, 3, 4], 'MatrixA':[[1, 2, 3],[4, 5, 6]]}

可以假设变量的顺序是固定的。因此,按照文本文件中出现的顺序列出 numpy 数组也可以。

最佳答案

from StringIO import StringIO
mytext='''%VectorA
1 2 3 4
%MatrixA
1 2 3
4 5 6
%VectorB
3 4 5 6 7'''

myfile=StringIO(mytext)
mydict={}
for x in myfile.readlines():
    if x.startswith('%'):
        mydict.setdefault(x.strip('%').strip(),[])
        lastkey=x.strip('%').strip()
    else:
        mydict[lastkey].append([int(x1) for x1 in x.split(' ')])

上面的 mydict 为:

{'MatrixA': [[1, 2, 3], [4, 5, 6]],
 'VectorA': [[1, 2, 3, 4]],
 'VectorB': [[3, 4, 5, 6, 7]]}

关于python - 在 python 中从文本文件中读取多个变量的聪明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058020/

相关文章:

Python:如何获取elasticsearch查询的总命中数

python - 如何在 OpenCV 上的不同颜色图之间进行转换?

python - 使用 root 安装 Setuptools - 出现 PythonPath 错误

python-3.x - 在训练期间将每个时期的层权重保存为 numpy 类型/数组?将 TensorFlow 变量转换为 numpy 数组?

python - 如何在 numpy 中使基于序列的函数更快?

python - Django- limit_choices_to 使用 2 个不同的表

python - 如何从文本文件向 OptionMenu 添加选项

python - 在 python 中 a/= 2.0 和 a = a/2.0 的结果是不一样的

Python,为什么 i=+1 不会导致无限循环?

Python numpy 索引超出轴零范围