如何从给定文件中读取矩阵?
我有一个文本文件,其中包含 N * M 维度的矩阵。
例如,input.txt 文件包含以下内容:
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,2,1,0,2,0,0,0,0
0,0,2,1,1,2,2,0,0,1
0,0,1,2,2,1,1,0,0,2
1,0,1,1,1,2,1,0,2,1
我需要编写 python 脚本,在其中可以导入矩阵。
我当前的 python 脚本是:
f = open ( 'input.txt' , 'r')
l = []
l = [ line.split() for line in f]
print l
输出列表是这样的
[['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'],
['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'],
['0,0,2,1,0,2,0,0,0,0'], ['0,0,2,1,1,2,2,0,0,1'], ['0,0,1,2,2,1,1,0,0,2'],
['1,0,1,1,1,2,1,0,2,1']]
我需要获取 int 形式的值。如果我尝试输入强制类型转换,它会抛出错误。
I have a text file which contains matrix of N * M dimensions.
For example the input.txt file contains the following:
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,2,1,0,2,0,0,0,0
0,0,2,1,1,2,2,0,0,1
0,0,1,2,2,1,1,0,0,2
1,0,1,1,1,2,1,0,2,1
I need to write python script where in I can import the matrix.
My current python script is:
f = open ( 'input.txt' , 'r')
l = []
l = [ line.split() for line in f]
print l
the output list comes like this
[['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'],
['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'], ['0,0,0,0,0,0,0,0,0,0'],
['0,0,2,1,0,2,0,0,0,0'], ['0,0,2,1,1,2,2,0,0,1'], ['0,0,1,2,2,1,1,0,0,2'],
['1,0,1,1,1,2,1,0,2,1']]
I need to fetch the values in int form . If I try to type cast, it throws errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
考虑
产生
注意,你必须用逗号分隔。
如果确实有空行,则更
改为
Consider
produces
Note that you have to split on commas.
If you do have blank lines then change
to
您可以简单地使用numpy.loadtxt。
易于使用,您还可以指定分隔符、数据类型等。
具体来说,您需要做的就是:
输出将是:
You can simply use numpy.loadtxt.
Easy to use, and you can also specify your delimiter, datatypes etc.
specifically, all you need to do is this:
And the output would be:
你可以这样做:
You can do this:
以下内容可以满足您的要求:
The following does what you want:
您不应该编写 csv 解析器,在读取此类文件时考虑
csv
模块,并在读取后使用with
语句关闭:You should not write your csv parser, consider the
csv
module when reading such files and use thewith
statement to close after reading:查看这个用于读取矩阵的一行小代码,
该代码将读取 3*3 阶的矩阵。
Check out this small one line code for reading matrix,
this code will read matrix of order 3*3.
输出:
output:
以下代码将上述输入转换为矩阵形式:
The following code converts the above input to matrix form: