Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.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
Python 使用deepcopy和substring操作的区别_Python_List - Fatal编程技术网

Python 使用deepcopy和substring操作的区别

Python 使用deepcopy和substring操作的区别,python,list,Python,List,我正在使用Python 2.7 我有一个列表lst=['a','b','c'] 如果我需要这个列表的副本,我通常做lst_cpy=lst[:] 我在软件包副本中遇到了一个函数deepcopy,它使我能够实现同样的功能 import copy lst_cpy_2 = copy.deepcopy(lst) 我可以互换使用这两种方法吗?或者这两种方法之间有什么区别吗 谢谢。因为没有方法/需要深度复制字符串,所以切片此特定列表具有相同的效果。但通常[:]执行序列的浅拷贝。对于简单列表,它们是相同的。如

我正在使用Python 2.7

我有一个列表lst=['a','b','c']

如果我需要这个列表的副本,我通常做lst_cpy=lst[:]

我在软件包副本中遇到了一个函数deepcopy,它使我能够实现同样的功能

import copy
lst_cpy_2 = copy.deepcopy(lst)
我可以互换使用这两种方法吗?或者这两种方法之间有什么区别吗


谢谢。

因为没有方法/需要深度复制字符串,所以切片此特定列表具有相同的效果。但通常[:]执行序列的浅拷贝。

对于简单列表,它们是相同的。如果列表中有其他结构,例如列表或字典中的元素,则它们会有所不同


L[:]创建一个新列表,新列表中的每个元素都是对旧列表中的值的新引用。如果其中一个值是可变的,则会在新列表中看到对它的更改。copy.deepcopy创建一个新列表,每个元素本身就是旧列表中值的深度副本。所以嵌套的数据结构在每一个级别都被复制。

我认为区别在于列表中的一个项目是列表、dict或其他可变对象。对于普通副本,对象在副本之间共享:

>>> l = ['a','b',[1,2]]
>>> l2 = l[:]
>>> l2[2].append('c')
>>> l
['a', 'b', [1, 2, 'c']]
但使用deepcopy时,对象也会被复制:

>>> l2 = copy.deepcopy(l)
>>> l2[2].append('d')
>>> l
['a', 'b', [1, 2, 'c']]
>>> l2
['a', 'b', [1, 2, 'c', 'd']]
他们是你的朋友。