晚安伴侣,
我是python编程的新手,我只是想知道你是否可以使用Points/Coordinate在python中访问2D数组?
有一个点的例子: point =(1,2)
并且你有一个矩阵,然后使用坐标访问矩阵的某个部分
Matrix [ point ] = 此处的样本值
谢谢,
文森特
流行的NumPy包提供了支持元组索引的多维数组:
import numpy
a = numpy.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
print a[1, 2]
point = (1, 2)
print a[point]
Run Code Online (Sandbox Code Playgroud)
没有任何外部库,Python中就没有"二维数组"这样的东西.只有嵌套列表,如numpy.array()上面的调用中所使用的那样.
你可以定义一个N by M Matrix并像这样访问它:
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
Run Code Online (Sandbox Code Playgroud)
在 Python 中,可以使用嵌套列表数据结构创建和引用 2D 矩阵。
但是,在矩阵代数坐标系中是 (column, row) ;
使用嵌套列表时会创建一个 (row, column) 坐标系。
要在 Python 中定义 2D 矩阵,请使用“嵌套列表”又名“列表列表”数据结构。
请注意,Python“列表”数据结构对应于Java“数组”数据结构。
要在坐标(列、行)处引用矩阵值:
coordinate_value = matrix[row][column]
Run Code Online (Sandbox Code Playgroud)
就像一维列表一样,索引从 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"
Run Code Online (Sandbox Code Playgroud)
如果你打算做大量的矩阵代数(特征向量、线性代数、矩阵变换等)——投资学习 numpy 模块。
如果您正在进行编码面试——嵌套列表是创建和使用 2D 矩阵的快捷方式。
干杯!