2016-09-19 52 views
0

如何读取文本文件,就好像它是一个矩阵,而不使用numphy或任何其他程序。例如:作为矩阵的文本文件

1, 2, 3, 4 
5, 6, 7, 8 
9, 10, 11, 12 

我想读列表,好像它是一个矩阵 - 读取每一列,好像它是一个类别L [0],L [1],L [2],和L [3]。我想采取每列的意思,但我需要知道如何相应地阅读文本文件。

谢谢你的帮助。

回答

0
matrix = [] # create an empty matrix. We'll add entries to it from the file soon 
with open('path/to/file') as infile: 
    for line in infile: # for each line in the file 
     row = [float(i) for i in line.strip().split(',')] # turn each element in the line into a floating point number 
     matrix.append(row) # treat that line of floating point numbers as a list, and add it as a row of the matrix 

cols = zip(*matrix) # transpose the matrix to get the columns 
means = [sum(col)/len(col) for col in cols] # compute the mean of each column