简体   繁体   中英

Values of variables inside a for-loop

I have an array a defined outside a for-loop. b is a variable assigned to be equal to a inside the loop. I change the values of b inside the loop which also alters a . Why/How does this happen?

>>> import numpy as np
>>> a = np.asarray(range(10))
>>> for i in range(5,7):
        b = a           #assign b to be equal to a
        b[b<i]=0        #alter b
        b[b>=i]=1
        print a

Output:

[0 0 0 0 0 1 1 1 1 1] #Unexpected!!
[0 0 0 0 0 0 0 0 0 0] 

Why is a altered when I don't explicitly do so?

Because when you do b = a only the reference gets copied. Both a and b point to the same object.

If you really want to create a copy of a you need to do for example:

import copy
...
b = copy.deepcopy(a)

numpy.asarray is mutable so, a and b pointed one location.

>>> a = [1,2,3]
>>> b = a
>>> id(a)
140435835060736
>>> id(b)
140435835060736

You can fix like this b = a[:] or b = copy.deepcopy(a)

id returns the “ identity ” of an object.

Use the slice operator to make a copy. = just gives it another name as it copies references.

b = a[:]

Will work fine.


According to @AshwiniChaudhary's comment, this won't work for Numpy arrays, the solution in this case is to

b = copy.deepcopy(a)

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