如何从给定文件中读取矩阵? [英] How to to read a matrix from a given file?

查看:84
本文介绍了如何从给定文件中读取矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含N * M维度的矩阵.

I have a text file which contains matrix of N * M dimensions.

例如,input.txt文件包含以下内容:

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

我需要编写python脚本,在其中可以导入矩阵.

I need to write python script where in I can import the matrix.

我当前的python脚本是:

My current python script is:

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 need to fetch the values in int form . If I try to type cast, it throws errors.

推荐答案

考虑

with open('input.txt', 'r') as f:
    l = [[int(num) for num in 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]]

请注意,您必须分割逗号.

Note that you have to split on commas.

如果您确实有空白行,请更改

If you do have blank lines then change

l = [[int(num) for num in line.split(',')] for line in f ]

l = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ]

这篇关于如何从给定文件中读取矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆