Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2D Array access with Points (x,y)

Tags:

python

I'm new to python programming, and I was just wondering if you can access a 2D array in python using Points/Coordinate?

Example you have a point: point = (1,2)

and you have a matrix, then you access a certain part of the matrix using a coordinate

Matrix[point] = a sample value here

like image 428
Vincent Bacalso Avatar asked Mar 27 '11 15:03

Vincent Bacalso


People also ask

How do you access values in a 2D array?

Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .

How do you access the elements of a two-dimensional array in Python?

The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array. If we mention only one index then the entire inner array is printed for that index position.

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

Indexing a Two-dimensional 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 I extract a value from a 2D array in Python?

Use the syntax array[:, [i, j]] to extract the i and j indexed columns from array . Like lists, NumPy arrays use zero-based indexes. Use array[:, i:j+1] to extract the i through j indexed columns from array .


1 Answers

The popular NumPy package provides multidimensional arrays that support indexing by tuples:

import numpy
a = numpy.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
print a[1, 2]
point = (1, 2)
print a[point]

Without any external libraries, there is no such thing as a "two-dimensional array" in Python. There are only nested lists, as used in the call to numpy.array() above.

like image 195
Sven Marnach Avatar answered Nov 03 '22 03:11

Sven Marnach