【问题标题】:Why does a list comprehension not append in python为什么列表推导不附加在python中
【发布时间】: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 中。

【问题讨论】:

    标签: python numpy


    【解决方案1】:
    kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
    #                             only 4 things ^^^^
    

    如果你想要 5 个元素,你想要range(5)

    【讨论】:

      【解决方案2】:
      >>> kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
      >>> len(kis)
      4
      

      所以最后一个索引是 3。当你:

      >>> kis.append(np.zeros(shape=(3,3)))
      >>> len(kis)
      5
      

      最后一个索引是 4。
      所以,kis[5] 超出范围

      【讨论】:

        猜你喜欢
        • 2018-12-05
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多