Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

python - After y = x, the value of x should not change, but why x changed in this script?

After running this script, both x and y equal 0, 3.14, 0, 3.14, 1.19, 3.14, 2.39, 3.14, 1, 3.14, 1

import numpy as np
x = np.concatenate([np.zeros(2), np.arange(0, 3.6, 0.6), np.ones(3)])
y = x;
y[1::2]  = np.pi
question from:https://stackoverflow.com/questions/65882811/after-y-x-the-value-of-x-should-not-change-but-why-x-changed-in-this-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The variable x contains a pointer to the array.

When writing y = x, you only assigned the pointer to the array to y. Because both variables point to the same array, any change made through x or y will be applied on the same data.

You can copy the array to have a different one: y = x.copy().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...