代码在不需要时自动实现变量 [英] Code actualising automatically variables when not desired

查看:71
本文介绍了代码在不需要时自动实现变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经隔离了较大代码的以下部分:

I have isolated the following part of a bigger code:

import numpy as np

population= np.random.normal(0,1,5)
individuals=population

print(population)

for i in range(len(individuals)):
    individuals[i]=0

print(population)

响应:

[-0.1791731  -0.0756427   0.44463943 -0.51173395  0.9121922 ]
[0. 0. 0. 0. 0.]

我不明白为什么结果不一样.

I can't understand why the results are not identical.

推荐答案

如果要复制numpy数组的内容,请使用.copy(),此刻正在执行的操作是将指针复制到列表. 因此,两个变量都指向相同的数据,因此,如果一个更改,它们都将更改.

use .copy() if you want to copy the content of the numpy array, what you are doing at the moment, is copying a pointer to the list. So both variables point to the same data, so if one changes they both change.

import numpy as np

population= np.random.normal(0,1,5)
individuals=population.copy()

print(population)

for i in range(len(individuals)):
    individuals[i]=0

print(population)

对于非数字列表,您可以使用[:]例如

For non-numpy lists you can use [:] eg

a = [1,2,3]
b = a[:]

这篇关于代码在不需要时自动实现变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆