灌装在迭代
问题描述:
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)
这是为什么? 感谢
答
因为每次循环首先要将的cube
到plane
一个元素,然后在循环套件,您分配一个不同的东西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]
>>>
因为你对迭代操作,而不是在阵列上的条带/图 – EdChum
那么,有没有办法用迭代器直接编辑立方体,还是必须坚持索引? – HansSnah
@HansSnah:在这种情况下,您需要使用'立方体中的plane:plane [:] = np.random.random(10000).reshape(100,100)'。 –