Reputation: 2147
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
Upvotes: 5
Views: 69176
Reputation: 775
In Python it's possible to create and reference 2D matrix using a nested list datastructure.
However, in Matrix Algebra coordinate systems are (column, row);
While using a nested list creates a (row, column) coordinate system.
To define a 2D matrix in Python use a "nested list" aka "list of lists" datastructure.
Note that the Python "list" datastructure corresponds to the Java "array" datastructure.
To reference a matrix value at coordinate (column, row):
coordinate_value = matrix[row][column]
Just like with 1D lists the index starts from 0...n
matrix = [
['a', 'b', 'c'],
['d', 'e', 'f', 'g'],
['h', 'i', 'j', 'k'],
]
print "value of row 0, column 2: " + matrix[0][2]
"the value of row 0, column 2 is: c"
If you're planning on doing substantial matrix algebra (eigenvectors, linear algebra, matrix transformations etc) -- invest in learning in the numpy module.
If you're performing a coding interview -- a nested list is a shortcut to create and work with a 2D matrix.
Cheers!
Upvotes: 8
Reputation: 601629
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.
Upvotes: 10
Reputation:
Part of the problem here is that you are trying to use 2d array and python doesn't actually support array's at all instead you use lists to create what you want have a look at
http://www.stev.org/post/2012/02/22/Python-2d-Arrays-dont-work.aspx
Upvotes: 1
Reputation: 4772
You could define an N by M Matrix and access it like this:
N = M = 5
Matrix = {(x,y):0 for x in range(N) for y in range(M)}
point1 = (1, 2)
Matrix[point1] = 2
print( Matrix[(3, 2)] ) # prints 0
Upvotes: 7