开发者

read from a text file. - Python

开发者 https://www.devze.com 2023-03-19 10:43 出处:网络
My question: For example, my text file is call \'f开发者_如何学编程eed.txt\'. and for inside, it likes that:

My question:

For example, my text file is call 'f开发者_如何学编程eed.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 ?


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

精彩评论

暂无评论...
验证码 换一张
取 消