2016-01-20 55 views
2

numpy的陣列我永遠無法理解爲什麼這不工作灌裝在迭代

import numpy as np 
cube = np.empty((10, 100, 100), dtype=np.float32) 

for plane in cube: 
    plane = np.random.random(10000).reshape(100, 100) 

與此cube仍然是空的(只是零)。我必須這樣做,使其工作:

for idx in range(10): 
    cube[idx] = np.random.random(10000).reshape(100, 100) 

這是爲什麼? 感謝

+1

因爲你對迭代操作,而不是在陣列上的條帶/圖 – EdChum

+0

那麼,有沒有辦法用迭代器直接編輯立方體,還是必須堅持索引? – HansSnah

+3

@HansSnah:在這種情況下,您需要使用'立方體中的plane:plane [:] = np.random.random(10000).reshape(100,100)'。 –

回答

0

因爲每次循環首先要將的cubeplane一個元素,然後在循環套件,您分配一個不同的東西plane,你從來沒有在cube改變任何東西。

Python是很酷,因爲你可以在外殼玩耍,並找出是如何工作的:

>>> a = [0,0,0,0] 
>>> for thing in a: 
    print(thing), 
    thing = 2 
    print(thing), 
    print(a) 


0 2 [0, 0, 0, 0] 
0 2 [0, 0, 0, 0] 
0 2 [0, 0, 0, 0] 
0 2 [0, 0, 0, 0] 
>>> 

Iterating Over Arrays