2024-04-18 16:11:41 发布
网友
我尝试加载多个存储在单个文本文件中的向量和矩阵(对于numpy)。 文件如下所示:
%VectorA 1 2 3 4 %MatrixA 1 2 3 4 5 6 %VectorB 3 4 5 6 7
理想的解决方案是使用dictionary对象,例如:
变量的顺序可以假定为固定的。因此,按照文本文件中出现的顺序列出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为:
mydict
上面给出
^{pr2}$mydict
为:相关问题 更多 >
编程相关推荐