I have a two-dimensional list with values that I changing. They need to be saved in another two-dimensional list (First list should not be changed).
I tried to set the values directly, but i'm getting this error: IndexError: list index out of range.
That's because nothing is copyied in fin_mat
.
How can i put changed values in new list?
for i, i_it in enumerate(mat):
for j, j_it in enumerate(mat[i]):
fin_mat[i][j] = mat[i-1][j] + mat[i+1][j] + mat[i][j-1] + mat[i][j+1]
UPD: Okay, I'll try to explain. Program should ask for a string, and convert it in a list that puted in another one to create a two-dimensional list:
b, st = [], [i for i in input().split()]
mat = []
it can be any long and to stop the input you must write: "end"
while (st[0] != 'end'):
st = [i for i in input().split()]
b.append(st)
if (st[0] == 'end'):
del b[-1]
Than you change string values into int
for j in b:
r = [int(item) for item in j]
mat.append(r)
print(mat)
After that, I need to created another matrix in which elements must be defined by this formula:
(i-1, j) + (i+1, j) + (i, j-1) + (i, j+1)
= fin_mat[ i ][ j ]
I can't just copy first list, and I can't change it because the values from the first list is in this formula.
I need to add values one by one in fin_mat
3 Answers 3
Create a copy of the original matrix first, like this:
import copy
fin_mat = copy.deepcopy(mat)
I think is easier to do it without enumerate like this example:
import cv2
img = cv2.imread("./Screenshot.png",1)
print(img.shape) # output is (961, 1744, 3)
for i in range(len(img)):
for j in range(len(img[i])):
img[i][j]=5
There are a few questions around the question itself, but I think I understand what you problem and question is.
Essentially, you do not only want to copy the list but also do some transformations without changing the original.
As previously pointed out the copying part is already answered in other questions. Regarding your IndexError, this is due to the logic of the loops; basically when i=0
you try to access mat[-1][j]
To correct this, you need to add some logic around what happens when you are on the edge of your matrix (in this example it's 0, but feel free to change):
fin_mat = fin_mat = [[0]*len(mat[0])]*len(mat) #creates an empty list of the same dimensions
for i, i_it in enumerate(mat):
for j, j_it in enumerate(mat[i]):
left = mat[i-1][j] if i > 0 else 0
right = mat[i+1][j] if i < len(mat)-1 else 0
top = mat[i][j-1] if j > 0 else 0
bottom = mat[i][j+1] if j < len(mat[i])-1 else 0
fin_mat[i][j] = left + right + top + bottom
Hope this helps
-
I know, I did this . But problem is not solvedMisha Salavatov– Misha Salavatov03/26/2019 10:59:10Commented Mar 26, 2019 at 10:59
-
mat
? Could you provide it?mat[-1][j]
and this obviously will happen when you get to j+1m
inmat[i-m+1]
which is not declared anywhere (not in the code you provided at least). Please provide a MCVE