python从文件读入矩阵_使用python从文本文件导入矩阵

1586010002-jmsa.png

I have two text files that have matrices written in them(not numpy matrices, so its a list of lists). These matrices are written in string format, so the text file looks like this :

[[1,2,3],[3,4,5],[6,7,8]],[[3,3,3],[5,6,7],.....

I want to read this matrix back from the text file using python. I can't read using numpy as it gives ValueError: could not convert string to float

Is there anyway to do this? Would it be easier if I just wrote the matrix as a numpy matrix in the first place(I need to change code of a previous program for that, and was just wondering if there was a python way of loading matrices when it was stored as a string in a text file)?

解决方案

You could make use of the ast module:

import ast

strArray = "[[1,2,3],[3,4,5],[6,7,8]]"

# evaluates the array in string format and converts it to a python array object

array = ast.literal_eval(strArray)

note:

For multiple nested arrays like you have, literal_eval will most likely convert the string into a tuple with nested arrays as elements. Just keep that in mind as you use this module.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值