简体   繁体   English

for循环内变量的值

[英]Values of variables inside a for-loop

I have an array a defined outside a for-loop. 我有一个数组a for循环以外定义。 b is a variable assigned to be equal to a inside the loop. b是分配为等于变量a循环内。 I change the values of b inside the loop which also alters a . 我在循环内更改b的值,这也会更改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? 为什么是a改变的时候,我不明确为什么这么做?

Because when you do b = a only the reference gets copied. 因为当您执行b = a仅引用被复制。 Both a and b point to the same object. ab指向同一个对象。

If you really want to create a copy of a you need to do for example: 如果你真的想创建的副本a你需要,例如做:

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

numpy.asarray is mutable so, a and b pointed one location. numpy.asarray是可变的,因此ab指向一个位置。

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

You can fix like this b = a[:] or b = copy.deepcopy(a) 您可以像这样修复b = a[:]b = copy.deepcopy(a)

id returns the “ identity ” of an object. id返回对象的“ 身份 ”。

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 根据@AshwiniChaudhary的评论,这不适用于Numpy数组,这种情况下的解决方案是

b = copy.deepcopy(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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