Python函数正在更改输入的值,但我不知道为什么 [英] Python function is changing the value of my input, and I can't figure out why
问题描述
这是我的第一个问题,因此,如果我正在发布此消息,请让我知道为什么以及将来如何避免它!
This is my first question, so if I'm being a total dweeb posting this, let me know why and how I can avoid it in the future!
我有一些python代码,应该只列出一个列表,并将第j个组件乘以-1.这是有问题的代码.
I have a bit of python code that should just take a list, and multiply the jth component by -1. This is the code in question.
def flip(spins,j):
z = spins
z[j] = z[j]*-1
return z
但是,我要注意的是,如果我尝试做类似的事情
However, what I am noticing is that if I try to do something like
spin = [1,1,1]
test = flip(spin,1)
它将为[test]分配适当的值[1,-1,1],但还将'spin'的值更改为[1,-1,1].我知道有些东西完全可以忽略,但是我一直盯着它看了2个小时,仍然看不到它.
it will assign the proper value [1,-1,1] to 'test', but it will also change the value of 'spin' to [1,-1,1]. I know there must be something totally obvious I'm overlooking, but I've been staring at this for 2 hours and still can't see it.
感谢您的帮助!
推荐答案
在函数中,z
和spins
引用相同的列表,也称为spin
的全局名称.如果您修改其中一个,则这些更改也可以通过其他名称看到.变量z
是多余的.
Inside your function, z
and spins
refer to the same list, which is also known by the global name of spin
. If you modify one, those changes are visible through the other names as well. The variable z
is superfluous.
如果您希望z
是spins
的副本,则只需执行以下操作:
If you want z
to be a copy of spins
then just do:
z = spins[:]
或:
z = list(spins)
这篇关于Python函数正在更改输入的值,但我不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!