Python的深拷贝

2025-12-26 21:41:51

1、打开电脑的运行输入‘cmd’,在弹出的命令行窗口输入‘python’

Python的深拷贝

Python的深拷贝

2、在python交互命令行输入以下内容:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD6

4)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import copy

>>> ll=['a','b']

>>> list1=['x',ll]

>>> print (list1)

['x', ['a', 'b']]

>>> list2 = copy.deepcopy(list1)

>>> print (list2)

['x', ['a', 'b']]

>>>

list1和list2内容完全一样,ll是嵌套的列表

Python的深拷贝

3、list1添加元素不会影响list2,测试代码如下:

>>> import copy

>>> ll=['a','b']

>>> list1=['x',ll]

>>> print (list1)

['x', ['a', 'b']]

>>> list2 = copy.deepcopy(list1)

>>> print (list2)

['x', ['a', 'b']]

>>> list1.append('new')

>>> print (list1)

['x', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>>

Python的深拷贝

4、list1修改元素不会影响list2,测试代码如下:

>>> import copy

>>> ll=['a','b']

>>> list1=['x',ll]

>>> print (list1)

['x', ['a', 'b']]

>>> list2 = copy.deepcopy(list1)

>>> print (list2)

['x', ['a', 'b']]

>>> list1.append('new')

>>> print (list1)

['x', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> list1[0]='0'

>>> print (list1)

['0', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>>

Python的深拷贝

5、嵌套列表ll的修改也只会影响list1,不会影响list2,代码如下:

>>> import copy

>>> ll=['a','b']

>>> list1=['x',ll]

>>> print (list1)

['x', ['a', 'b']]

>>> list2 = copy.deepcopy(list1)

>>> print (list2)

['x', ['a', 'b']]

>>> list1.append('new')

>>> print (list1)

['x', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> list1[0]='0'

>>> print (list1)

['0', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> ll[0] = 'change'

>>> print (list1)

['0', ['change', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>>

Python的深拷贝

6、嵌套列表ll的添加元素也只会影响list1,不会影响list2,代码如下:

>>> import copy

>>> ll=['a','b']

>>> list1=['x',ll]

>>> print (list1)

['x', ['a', 'b']]

>>> list2 = copy.deepcopy(list1)

>>> print (list2)

['x', ['a', 'b']]

>>> list1.append('new')

>>> print (list1)

['x', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> list1[0]='0'

>>> print (list1)

['0', ['a', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> ll[0] = 'change'

>>> print (list1)

['0', ['change', 'b'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>> ll.append('aa')

>>> print (list1)

['0', ['change', 'b', 'aa'], 'new']

>>> print (list2)

['x', ['a', 'b']]

>>>

Python的深拷贝

7、这是因为深拷贝不同于浅拷贝,浅拷贝如果有嵌套,嵌套内容的更改会同时影响到拷贝方和被拷贝方,因为指向同一个地址,而深拷贝其实是另外开辟了内存空间,和原来的内容完全一致,但是互相独立。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢