Python的深拷贝

 时间:2026-02-16 10:22:42

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

  • 如何在windows 7下访问Linux分区
  • 怎么给自己编译的易语言程序写注册机
  • 如何创建Hyper-V的虚拟硬盘
  • 易语言-位或-实例讲解
  • 如何使用Powershell程序查询当前的日期和时间?
  • 热门搜索
    柒怎么读 三角形的高怎么求 腐竹怎么泡最快 鞋子怎么画 月经为什么叫大姨妈 为什么要入团 鸡蛋撞地球的做法 乳头为什么是黑色的 套五笔怎么打 怎么变白