如何在python中按值分配 [英] How can I assign by value in python
问题描述
我知道,由于Python的工作方式x = []; y = x; x.append(1); y
将打印[1]
.但是,相反,
I understand that, due to the way Python works x = []; y = x; x.append(1); y
will print [1]
. However, the reverse, say,
z = [1,2]
temp = z
temp[1] = 3
z,temp
将打印([1,3],[1,3])
.如果我理解正确,那么z
和temp
都指向同一列表,因此更改列表将更改另一个列表,因为列表是可变的.如何防止这种情况发生?即,我想进行一个for循环,将z
复制到temp
,以不同的方式进行更改,然后将其推送到队列中.为此,z
必须始终包含基本数组,因此我需要更改temp
时不要更改z
.
will print ([1,3],[1,3])
. If I understand correctly, both z
and temp
point to the same list, so changing one will change the other, seeing as lists are mutable. How can I prevent this from happening? Namely, I want to make a for loop that will copy z
into temp
, change it in different ways, and push it onto a queue. For that to work, z
must always contain the base array, therefore I need that changing temp
doesn't change z
.
我尝试将z更改为元组,以便z=z,
,然后调用z[0]
而不是z
.但这仍然不能解决我的问题.
I tried changing z into a tuple so that z=z,
, then calling z[0]
instead of z
. Still this doesn't solve my problem.
推荐答案
复制列表很容易...只需对其切片:
Copying a list is easy ... Just slice it:
temp = z[:]
这将创建一个浅表副本-列表中元素的突变将显示在z
中的元素中,但不会直接更改为temp
.
This will create a shallow copy -- mutations to elements in the list will show up in the elements in z
, but not changes to temp
directly.
出于更一般的目的,python有一个copy
模块可供您使用:
For more general purposes, python has a copy
module that you can use:
temp = copy.copy(z)
或者,也许:
temp = copy.deepcopy(z)
这篇关于如何在python中按值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!