Read From A Text File. - Python
My question: For example, my text file is call 'feed.txt'. and for inside, it likes that: 2 # two means 'there are two matrix in this file' 3 # three means 'the below one is a 3*3
Solution 1:
Okay, gonna take you through this step by step. If 'file'
is your file name, try:
matrices = [] # The list you'll be keeping your matrices inwithopen('file') as f:
num_matrices = int(f.readline())
for mat_index inrange(num_matrices):
temp_matrix = [] # The list you'll keep the rows of your matrix in
num_rows = int(f.readline())
for row_index inrange(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)
Then each of your matrices will be stored in an index of matrices
. You can iterate through these as you like:
for my_matrix in matrices:
# Do something hereprint my_matrix
For the second part on summing the rows, you have two options if you want this to work correctly. Either use i
to index into a row of your list:
for i inrange(len(my_matrix):
total = sum(my_matrix[i])
print(total)
Or use the more Pythonic way and iterate directly over your sub-lists:
forrowin my_matrix:
total =sum(row)
print(total)
If you want to save each of these individual results for later use, you'll have to make a list for your results. Try:
>>>sumz = []>>>for row in my_matrix:
sumz.append(sum(row))
>>>sumz
[15, 15, 15]
Post a Comment for "Read From A Text File. - Python"