python 深浅拷贝

1.浅拷贝

  数据半共享,只拷贝父对象,不会拷贝对象的内部的子对象

  方法:

  (1)a.copy()

  (2)list(a)

  (3)a[:]

2.深拷贝

  数据不共享,拷贝父对象和内部的子对象

  方法:

  (1)copy.copy(a)

  (2)copy.deepcopy(a)

# coding:utf-8

a = [1, 2, 3, 4]
# 浅拷贝 
b = a.copy()
b2 = list(a)
b3 = a[:]
a[3] = 'surprise'
a[2] = [0, -1, -2]
print(f'a\t{a}\nb\t{b}\nb2\t{b2}\nb3\t{b3}')

# 深拷贝 
import copy
c = [5, 6, 7, [8, 9, 10]]
c[0] = ['5']
c[3][2] = [1, 2, 3]
d = copy.copy(c)
d2 = copy.deepcopy(c)
print(f'c\t{c}\nd\t{d}\nd2\t{d2}')

输出结果:

a [1, 2, [0, -1, -2], 'surprise']
b [1, 2, 3, 4]
b2 [1, 2, 3, 4]
b3 [1, 2, 3, 4]
c [['5'], 6, 7, [8, 9, [1, 2, 3]]]
d [['5'], 6, 7, [8, 9, [1, 2, 3]]]
d2 [['5'], 6, 7, [8, 9, [1, 2, 3]]]

上一篇:WordPress主题 柒比贰高级商用主题 b2 v2.5.1 功能强大 非常火的一款WordPre


下一篇:Calendar时间操作常用方法