How to access elements in a 2D array?

I am new to python and I would like to understand how you can manipulate array elements. If I have, for example:

a= ( a11 a12 a13 ) and b = (b11 b12 b13) a21 a22 a23 b21 b22 b23 

I defined them in python, for example:

 a=[[1,1],[2,1],[3,1]] b=[[1,2],[2,2],[3,2]] 

I saw that I cannot refer to a[1][1] , but to a[1] , which gives me the result [2,1] . So, I donโ€™t understand how can I access the second line of these arrays? Will it be a21, a22, a23, b21, b22, b23 ? And how would I do to multiply them by c1 = a21*b21, c2 = a22*b22 , etc.?

+14
source share
6 answers

If you

 a=[[1,1],[2,1],[3,1]] b=[[1,2],[2,2],[3,2]] 

Then

 a[1][1] 

Will work fine. It points to the second column of the second row as you like.

I'm not sure what you did wrong.

To multiply the cells in the third column, you can simply do

 c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of lines.

Edit: the first number is the column, the second number is the row with the current layout. Both are numbered from zero . If you want to change the order you can do

 a = zip(*a) 

or you can create it this way:

 a=[[1, 2, 3], [1, 1, 1]] 
+13
source

If you want to do a lot of calculations using a 2d array, you should use a NumPy array instead of a list of sockets.

for your question, you can use: zip (* a) to transpose it:

 In [55]: a=[[1,1],[2,1],[3,1]] In [56]: zip(*a) Out[56]: [(1, 2, 3), (1, 1, 1)] In [57]: zip(*a)[0] Out[57]: (1, 2, 3) 
+3
source

Seems to work here:

 >>> a=[[1,1],[2,1],[3,1]] >>> a [[1, 1], [2, 1], [3, 1]] >>> a[1] [2, 1] >>> a[1][0] 2 >>> a[1][1] 1 
0
source

a[1][1] working properly. Do you mean a11 as the first element of the first line? Because it will be [0] [0].

0
source

Take a close look at how many brackets your array has. I met an example when a function returned an answer with an extra bracket, for example:

 >>>approx array([[[1192, 391]], [[1191, 409]], [[1209, 438]], [[1191, 409]]]) 

And it didnโ€™t work

 >>> approx[1,1] IndexError: index 1 is out of bounds for axis 1 with size 1 

This may open the brackets:

 >>> approx[:,0] array([[1192, 391], [1191, 409], [1209, 438], [1191, 409]]) 

Now you can use the standard entry for accessing the element:

 >>> approx[:,0][1,1] 409 
0
source

If you have this:

 a = [[1, 1], [2, 1],[3, 1]] 

You can easily access this with:

 print(a[0][2]) a[0][1] = 7 print(a) 
0
source

All Articles