更改一个列表也会意外地更改另一个列表 [英] Changing one list unexpectedly changes another, too
本文介绍了更改一个列表也会意外地更改另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表格列表
v = [0,0,0,0,0,0,0,0,0]
代码中的某处
vec=v向量[5]=5
这会同时改变 v
和 vec
:
为什么 v
会发生变化?
解决方案
为什么 v 会发生变化?
vec
和 v
都是引用.
当编码 vec = v
时,您将 v
地址分配给 vec
.因此,改变 v
中的数据也会改变"vec
.
如果你想有两个不同的数组使用:
vec = list(v)
I have a list of the form
v = [0,0,0,0,0,0,0,0,0]
Somewhere in the code I do
vec=v
vec[5]=5
and this changes both v
and vec
:
>>> print vec
[0, 0, 0, 0, 0, 5, 0, 0, 0]
>>> print v
[0, 0, 0, 0, 0, 5, 0, 0, 0]
Why does v
change at all?
解决方案
Why does v change at all?
vec
and v
are both references.
When coding vec = v
you assign v
address to vec
.
Therefore changing data in v
will also "change" vec
.
If you want to have two different arrays use:
vec = list(v)
这篇关于更改一个列表也会意外地更改另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文