A
A
Alexander2020-12-16 11:22:35
Python
Alexander, 2020-12-16 11:22:35

How to refer to each element of the original matrix in Python?

I have a code that works with a matrix in a file and works with the codes module_1 module_2 and module_3

import csv
from matplotlib.pyplot import matshow, show
from module_1 import task_1
from module_2 import task_2
from module_3 import task_3
def read(csvfile):
    with open(csvfile, 'r') as file:
        r = list(csv.reader(file))
    for x in range(len(r)):
        for y in range(len(r[x])):
            r[x][y] = int(r[x][y])
    return r
def write(matrix, name = "result.csv"):
    with open(name, 'w') as file:
        for x in range(len(matrix)):
            for y in range(len(matrix[x])):
                if y == len(matrix[x]) - 1:
                    file.write(str(matrix[x][y]) + "\n")
                else:
                    file.write(str(matrix[x][y]) + " ")
t1 = task_1(read("tekst.csv"))
for x in range(len(t1)):
    print(t1, end='\n')
print('\n')
t2 = task_2(read("tekst.csv"))
for x in range(len(t2)):
    for y in range(len(t2[x])):
        print(t2[x][y], end=' ')
    print()
t3 = task_3(read("tekst.csv"))
for x in range(len(t3)):
    print(t3[x], end='\n')
print('\n')
write(t2)
matshow(t2)
show()

module_1 changes the matrix to zeros
def task_1(m): 
    d = [0]*len(m)
    return d

And the output is:
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]

But I need the output to be:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

Similarly, in module_3, it removes the last 4 rows of the matrix:
def task_3(m):
    return m[:-4]

Conclusion:
[1, 2, 3, 4, 5, 6, 7, 8]
[8, 7, 6, 5, 4, 3, 2, 1]
[2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2]

And you need:
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2

Input data in tekst.csv file
1,2,3,4,5,6,7,8
8,7,6,5,4,3,2,1
2,3,4,5,6,7,8,9
9,8,7,6,5,4,3,2
1,3,5,7,9,7,5,3
3,1,5,3,2,6,5,7
1,7,5,9,7,3,1,5
2,6,3,5,1,7,3,2

help me please

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuriy Vorobyov, 2020-12-16
@Sever_Ego

Replace your output with, for example, t1:

for x in range(len(t1)):
  print(*t1, sep=" ")

And for t3:
for x in range(len(t3)):
  print(*t3[x], sep=" ")

L
Leonid, 2020-12-16
@LeoMay

Do you need screen output? Or saving each row of the matrix as a row?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question