迭代时填充numpy数组

时间:2016-01-20 15:34:53

标签: python 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 个答案:

答案 0 :(得分:0)

因为循环的每次迭代,您首先将cube的元素分配给plane,然后在循环套件中为plane分配不同的内容,并且您永远不会更改cube中的任何内容1}}。

Python很酷,因为你可以在shell中玩游戏并弄清楚它是如何工作的:

>>> 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

相关问题