从文本文件读取 - Python
我的问题是:
比如,我有一个文本文件叫做 'feed.txt',里面的内容是这样的:
2 # two means 'there are two matrix in this file'
3 # three means 'the below one is a 3*3 matrix'
1 8 6
3 5 7
4 9 2
4 # four means 'the below one is a 4*4 matrix'
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
这个文件里有两个矩阵。第一个是 [[1,8,6],[3,5,7],[4,9,2]]
,第二个是 [[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]]
。
我想知道怎么在Python中把这两个矩阵用作一个列表,像这样:
list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]
然后我可以得到 sam(list_[0])=15
。
另外,里面有三行数据:
list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]
我想计算每一行的总和。所以我这样做:
list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]
for i in range(len(list_)):
sum_=sum(list_[i])
print(sum_)
但是我没有得到三个数字,只得到了一个数字,为什么呢?
1 个回答
4
好的,我会一步一步带你走。如果 'file'
是你的文件名,可以试试:
matrices = [] # The list you'll be keeping your matrices in
with open('file') as f:
num_matrices = int(f.readline())
for mat_index in range(num_matrices):
temp_matrix = [] # The list you'll keep the rows of your matrix in
num_rows = int(f.readline())
for row_index in range(num_rows):
line = f.readline()
# Split the line on whitespace, turn each element into an integer
row = [int(x) for x in line.split()]
temp_matrix.append(row)
matrices.append(temp_matrix)
这样,每个矩阵都会存储在 matrices
的一个索引里。你可以根据需要遍历这些矩阵:
for my_matrix in matrices:
# Do something here
print my_matrix
关于第二部分的行求和,如果你想让它正确工作,有两种选择。你可以用 i
来索引你的列表中的一行:
for i in range(len(my_matrix):
total = sum(my_matrix[i])
print(total)
或者使用更符合 Python 风格的方法,直接遍历你的子列表:
for row in my_matrix:
total = sum(row)
print(total)
如果你想把每个结果保存起来以便后续使用,你需要为结果创建一个列表。可以试试:
>>> sumz = []
>>> for row in my_matrix:
sumz.append(sum(row))
>>> sumz
[15, 15, 15]