我只是想將項目添加到列表中,我不能!我的代碼:爲什麼我無法正確地將項目添加到Python列表中?
import numpy as np
data = [[]] * 10
for i in range(0, len(data)):
slice = np.random.randn(100, 100, 3)
print('before: ', np.shape(data))
print('slice: ', np.shape(slice))
data[i].append(slice)
print('after: ', np.shape(data))
結果如下:
before: (10, 0)
slice: (100, 100, 3)
after: (10, 1, 100, 100, 3)
...
before: (10, 0)
slice: (100, 100, 3)
after: (10, 10, 100, 100, 3)
所以,(100,100,3)未在data[0]
插入到正確的位置,但創建額外的尺寸!爲什麼?我該如何避免它?
結果列表的正確的尺寸應爲(10,,100,100,3) - 不(10,10 ,100,100,3)。
'數據=名單()'然後'data.append(片)' – Sraw
或'數據[i] = slice' – Sraw
你只需要確保數據只包含10時它被初始化。然後你可以追加。 –