Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the elements of a 2D array?

Tags:

I would like to understand how one goes about manipulating the elements of a 2D array.

If I have for example:

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

I have defined them in python as 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 a result of [2,1]. So, I don't understand how do I access the second row of these arrays? That would be a21, a22, a23, b21, b22, b23? And how would I do in order to multiply them as c1 = a21*b21, c2 = a22*b22, etc ?

like image 513
caran Avatar asked Aug 11 '11 07:08

caran


People also ask

How are the elements accessed in 2D array in C?

Accessing Elements of Two-Dimensional Array in C To access an element at position (i, j), we use array_name[i - 1][j - 1]. Thus the element at the 4th row and 5th column will be accessed by A[3][4].

How do you access elements in a Numpy 2D array?

To access elements in this array, use two indices. One for the row and the other for the column. Note that both the column and the row indices start with 0. So if I need to access the value '10,' use the index '3' for the row and index '1' for the column.

How do you access the elements of a 2D array using pointers?

The elements of 2-D array can be accessed with the help of pointer notation also. Suppose arr is a 2-D array, we can access any element arr[i][j] of the array using the pointer expression *(*(arr + i) + j).

How do you access the elements of a 2D list in Python?

In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.


2 Answers

If you have

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, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

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

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a) 

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]] 
like image 192
agf Avatar answered Sep 20 '22 09:09

agf


If you want do many calculation with 2d array, you should use NumPy array instead of nest list.

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) 
like image 33
HYRY Avatar answered Sep 21 '22 09:09

HYRY