如何从给定文件中读取矩阵?

时间:2011-10-01 07:25:32

标签: python file-io

我有一个包含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形式获取值。如果我尝试输入强制转换,则会抛出错误。

8 个答案:

答案 0 :(得分:24)

考虑

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]]

请注意,您必须用逗号分隔。


如果您有空白行,请更改

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() != "" ]

答案 1 :(得分:12)

您只需使用numpy.loadtxt即可。 易于使用,您还可以指定分隔符,数据类型等。

具体来说,您需要做的就是:

import numpy as np
input = np.loadtxt("input.txt", dtype='i', delimiter=',')
print(input)

输出结果为:

[[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 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]]

答案 2 :(得分:2)

你可以这样做:

fin = open('input.txt','r')
a=[]
for line in fin.readlines():
    a.append( [ int (x) for x in line.split(',') ] )

答案 3 :(得分:1)

以下是您想要的:

l = []
with open('input.txt', 'r') as f:
  for line in f:
    line = line.strip()
    if len(line) > 0:
      l.append(map(int, line.split(',')))
print l

答案 4 :(得分:1)

您不应该编写csv解析器,在阅读此类文件时请考虑csv模块,并在阅读后使用with语句关闭:

import csv

with open('input.txt') ad f:
    data = [map(int, row) for row in csv.reader(f)]

答案 5 :(得分:1)

查看这个小的一行代码以读取矩阵,

matrix = [[input() for x in range(3)] for y in range(3)]

此代码将读取订单3 * 3的矩阵。

答案 6 :(得分:0)

p <- ggplot(mtcars0, aes(mpg, wt, fill = cyl)) + 
  geom_bar(stat = "identity", width = 2) + 
  facet_grid(~ cyl ~. ) + 
  geom_text(aes(mpg, wt, label = MeanMpg), size = 4, x = 15, y = 5) +
  scale_fill_manual(values = c("royalblue", "orange", "orangered"))
p

输出:

import numpy as np
f = open ( 'input.txt' , 'r')
l = []
l = np.array([ line.split() for line in f])
print (l)
type(l)
     

numpy.ndarray

答案 7 :(得分:0)

以下代码将上述输入转换为矩阵形式:

f = open ('input.txt' , 'r')
l = []
l = [line.split() for line in f]
l=np.array(l)
l=l.astype(np.int)