簡體   English   中英

為什么列表推導不附加在python中

[英]Why does a list comprehension not append in python

我創建了一個列表推導,試圖模仿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中。

kis= [ np.zeros(shape=(3,3)) for t in range(1, 5) ]
#                             only 4 things ^^^^

如果需要5個元素,則需要range(5)

>>> 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]超出范圍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM