我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
如果你真的想要一个矩阵,你最好使用numpy。numpy中的矩阵运算通常使用二维数组类型。创建新阵列有多种方法;其中最有用的是zeros函数,它接受一个形状参数并返回一个给定形状的数组,值初始化为零:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
以下是创建二维数组和矩阵的一些其他方法(为了紧凑,去掉了输出):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy也提供了一种矩阵类型,但它不再推荐用于任何用途,将来可能会从numpy中删除。
其他回答
下面是一个用于初始化列表列表的简短符号:
matrix = [[0]*5 for i in range(5)]
不幸的是,将其缩短为5*[5*[0]这样的长度并不能真正起作用,因为您最终会得到相同列表的5个副本,因此当您修改其中一个副本时,它们都会发生变化,例如:
>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]
如果您希望能够将其视为2D阵列,而不是被迫根据列表进行思考(在我看来更自然),可以执行以下操作:
import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()
结果是一个列表(不是NumPy数组),您可以用数字、字符串等覆盖各个位置。
如果要创建空矩阵,正确的语法是
matrix = [[]]
如果你想生成一个大小为5、填充有0的矩阵,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]
在Python中,您将创建一个列表列表。您不必提前声明维度,但可以这样做。例如:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
现在矩阵[0][0]==2,矩阵[1][0]==3。您还可以使用列表理解语法。本示例使用它两次来构建“二维列表”:
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
通常,go to模块是NumPy:
import numpy as np
# Generate a random matrix of floats
np.random.rand(cols,rows)
# Generate a random matrix of integers
np.random.randint(1, 10, size=(cols,rows))