【发布时间】:2015-03-10 00:38:39
【问题描述】:
我创建了一个列表理解,试图模仿 3x3 矩阵的 Matlab 单元。
kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
这就像 Matlab 中的一个单元格有五个 3x3 零矩阵。我可以访问它们
kis[0]
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
我可以将它们修改为
>>> kis[0][0][1]=2
>>> kis[0]
array([[ 0., 2., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> kis[0][0][1]
2.0
现在有 5 个元素,比如说我想添加第六个元素。
kis.append(np.zeros(shape=(3,3)))
当我尝试访问应该是 3x3 零矩阵的第六个单元格元素时,我遇到了这个错误:
>>> kis[5]
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
kis[5]
IndexError: list index out of range
那么如何将更多的 3x3 矩阵添加到列表中?为什么上述方法不起作用?以上代码在 Python 2.7.9 中。
【问题讨论】: