Python numpy 数组正在循环中重写 - 不应该这样做



使用 Anaconda,我编写了一个简单的代码,我试图弄清楚数组在定义后如何在 for 循环中不断重写。我编写名为 box 的数组(随机 0 或 1(,并将一个新的数组持有者定义为我想单独保留的数组的"副本"。但是,盒子不断被重写,我只是不知道它应该如何做到这一点。

#FUNCTIONS
def initialize():
    config = np.zeros([n, n])
    for x in range(n):
        for y in range(n):
            if np.random.rand() < p:
                config[x, y] = 1
    return config
def roller(x):
    test1 = np.roll(x,1,axis=0)
    test2 = np.roll(x,1,axis=1)
    test3 = np.roll(x,-1,axis=1)
    test4 = np.roll(x,-1,axis=0)
    hold = np.sum([test1,test2,test3,test4],axis=0)
    return hold
def loop(steps,holder,store_config):
    for t in range(steps):
        tot = roller(holder)
        for x in range(n):
            for y in range(n):
                if tot[x,y] >= 4:
                    holder[x,y] = 1
                else: 
                    holder[x,y] = 0
        store_config[:,:,t] = holder
def func():
    start = time.time()
    time_steps = 20
    store_config = np.zeros([n,n,time_steps])
    loop(time_steps,holder,store_config)
    end = time.time()
    print(end - start, np.sum(store_config))
#CONSTANTS
n = 100
p = .2
box = initialize() #Array to leave ALONE
print(np.sum(box))
#Action
holder = box #Array to manipulate and redefine as box
func()
print(np.sum(box))

如果你从 np.sum(box( 的输出值应该匹配之前和之后 func(( 运行,但他们从来没有这样做。目的是当我重新运行func((时,它会吐出一个值,但只是迭代相同的定义"box"数组,但它不断被重写。我不明白这怎么可能。我认为数组被视为函数中的变量,它们不是全局的?三个部分 #Functions、#Constants 和 #Action 中的每一个都将位于 Conda 笔记本中各自的单元格中。

我认为您遇到的问题是数组,就像列表和字典一样,是通过引用分配的。 无论是变量赋值还是作为传递给函数的参数,都会发生这种情况。

def f(x):
    x[0] = 0
    return x
a = array([1, 1])
b = f(a)

将导致ab相等,因为x纵然后返回。 如果要保留a,必须先复制数组:

def f(x):
    x_ = x.copy()
    x_[0] = 0
    return x_

我希望这能澄清一些事情。

holder = box行不会创建数组的新副本,它会导致holder指向与box相同的数组。由于您的代码修改了holder ,因此您希望holder指向box的副本,以便它不会被覆盖。您可以使用np.copy()执行此操作,如下所示:

holder = np.copy(box)

相关内容

最新更新