如何在不使用numphy或任何其他程序的情况下读取文本文件,就像它是一个矩阵一样。例如:
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
我想把列表看作是一个矩阵 - 读取每一列,好像它是一个类别L [0],L [1],L [2]和L [3]。我想取每列的意思,但我需要知道如何相应地阅读文本文件。
感谢您的帮助。
答案 0 :(得分: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