开发者

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

开发者 https://www.devze.com 2023-02-19 21:31 出处:网络
I\'m new to python programming, and I was just wondering if you can access a 2D array in python using Points/Coordinate?

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 ma开发者_运维知识库trix using a coordinate

Matrix[point] = a sample value here


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.


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"

Use Cases

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!


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号