Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Python列表don';t在分配给其他列表时,不能正确更改值_List_Python 3.x_Variable Assignment - Fatal编程技术网

List Python列表don';t在分配给其他列表时,不能正确更改值

List Python列表don';t在分配给其他列表时,不能正确更改值,list,python-3.x,variable-assignment,List,Python 3.x,Variable Assignment,我在Python 3代码中遇到了一个错误,经过大量调试后,我发现Python似乎没有正确分配列表: $ python3 Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >&g

我在Python 3代码中遇到了一个错误,经过大量调试后,我发现Python似乎没有正确分配列表:

$ python3
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test_1 = [12, 34]
>>> test_1
[12, 34]
>>> test_2 = [12, 34]
>>> test_2
[12, 34]
>>> test_2 = test_1
>>> test_2
[12, 34]
>>> test_1[0] = 'This changes in both arrays!'
>>> test_1
['This changes in both arrays!', 34]
>>> test_2
['This changes in both arrays!', 34]
>>> 

为什么会这样?这是有意的吗?如何阻止它发生???

当您执行
test_2=test_1
时,您正在使test_2指向test_1所指向的列表

你可以这样做:

>>> test_2 = test_1.copy()

这是预期的行为。Python列表按引用传递。这意味着,当您分配一个列表时,它不会复制该列表并将该新列表分配给新变量,而是使两个变量指向同一个基础列表。这在很多情况下都很有用。但你似乎真的想复制这份名单。为此,请执行以下操作:

test_2 = list(test_1)

或者
test_2=test_1[:]