简体   繁体   中英

Filling numpy array upon iteration

I never understood why this is not working

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)

With this the cube is still empty (just zeros). I have to do it like that to make it work:

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

Why is that? thanks 😊

Because each iteration of the loop you first assign an element of cube to plane then in the loop suite you assign a different thing to plane and you never change anything in cube .

Python is cool because you can play around in the shell and figure out how things work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM