我想定义一个没有初始化长度的二维数组,如下所示:
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中删除。
其他回答
我在逗号分隔的文件中阅读如下:
data=[]
for l in infile:
l = split(',')
data.append(l)
列表“data”是带有索引数据[row][col]的列表列表
要声明一个零(1)矩阵:
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
或numpy.ones((x,y))例如
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
甚至三维都是可能的。(http://www.astro.ufl.edu/~warner/prog/python.html请参见-->多维数组)
如果你只需要一个二维容器来容纳一些元素,你可以方便地使用字典来代替:
Matrix = {}
然后您可以执行以下操作:
Matrix[1,2] = 15
print Matrix[1,2]
这是因为1,2是一个元组,您将其用作索引字典的键。结果类似于哑稀疏矩阵。
如osa和Josap Valls所示,您还可以使用Matrix=collections.defaultdict(lambda:0),以便丢失的元素具有默认值0。
Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,只应在代码的非性能关键部分使用。
Use:
matrix = [[0]*5 for i in range(5)]
第一个维度的*5有效,因为在这个级别上数据是不可变的。
下面是一个用于初始化列表列表的简短符号:
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]]