EN VI

Python - From a list of matrices, create an array containing the i-th and j-th element of each matrix?

2024-03-12 20:30:11
How to Python - From a list of matrices, create an array containing the i-th and j-th element of each matrix

I have a list of matirces each containing pixel values of a screen at a given moment. Matrix1 contains pixel values at moment1, matrix2 contains pixel values at moment2 and so on. Lets say I want to take a look at how one individual pixel evolves throughout time. I created some dummy matrices to test how that would work and put them in mylist:

m1=[[1,2],[3,4]]
m2=[[1,2],[3,4]]
m3=[[5,6],[7,8]]

mylist=[m1,m2,m3]

print(mylist)

Then I wanted to select the (0,0) element of the second matrix:


print(mylist[1][1][0])

This gives me the expected output 1. Then I wanted to generalize it and pick the (0,0) element of every matrix, which should give me the output mynewlist=[1,1,5]:

mynewlist=[]

for i in 2:
    mynewlist.append(mylist[i][1][0])
    
print("hello hello")
print(mynewlist)

However, it gives me the error message:

for i in 2:
TypeError: 'int' object is not iterable 

What did I do wrong? How can I bypass this problem? Is there any other (most propably smoother and better) way to select the (i,j) element from each matrix?

Solution:

A better aproach would be to directly loop through the ellement of mylist as:

   mynewlist = [] 
   for image in mylist:
       mynewlist.append(image[1][0])

This makes your code more readible. And now it doesn't matter how many images you have in your initial list.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login