Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

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

There are two matrix in side this file. [[1,8,6],[3,5,7],[4,9,2]] and [[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]].

I want to know how can I use these two matrix in Python as a list which like

list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]

and then I can get sam(list_[0])=15.

also. there are three rows in

list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]

and I want to do the sum of each row. So I did

list_=[[1, 8, 6], [3, 5, 7], [4, 9, 2]]

for i in range(len(list_)):

sum_=sum(list_[i])

print(sum_)

but I cannot get three numbers, I only get one number, why ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 here
    print 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 in range(len(my_matrix):
    total = sum(my_matrix[i])
    print(total)

Or use the more Pythonic way and iterate directly over your sub-lists:

for row in 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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...