愚公移山日记·38

愚公移山日记·38

今天的内容比较多可能会写好几篇(1)
简单不可变类型的拷贝

# 简单不可变类型都是浅拷贝
# 元组,字符串,数字 都是不可变
import copy


def test_copy():
    tiple1 = (1, 2, 3)
    print('tuple1 = ', tiple1, id(tiple1))
    # 对简单不可变类型进行浅拷贝
    # 等价于 tuple2 = tiple1
    tuple2 = copy.copy(tiple1)
    print('tuple2 = ', tuple2, id(tuple2))


tiple1 = (1, 2, 3)
print('tuple1 = ', tiple1, id(tiple1))
# 对简单不可变类型进行浅拷贝
# 等价于 tuple2 = tiple1
tuple2 = copy.deepcopy(tiple1)
print('tuple2 = ', tuple2, id(tuple2))


# 简单不可变类型 无论深拷贝还是浅拷贝 都无法创建新的内存空间

复杂可变类型的拷贝

# 含有嵌套关系的
import copy


def test():
    A = [1, 2]
    B = [3, 4]
    C = [A, B]

    print('A = ', A, id(A))
    print('B = ', B, id(B))
    print('C = ', C, id(C))
    print('C[0]', C[0], id(C[0]))
    # 复杂可变类型进行浅拷贝
    D = copy.copy(C)
    print('D = ', D, id(D))
    print('D[0] = ', D[0], id(D[0]))

    # 修改A的
    A[0] = 10
    print('A = ', A, id(A))
    print('D[0] = ', D[0], id(D[0]))


def test2():
    A = [1, 2]
    B = [3, 4]
    # [[1, 2],[3, 4]]
    C = [A, B]

    print('A = ', A, id(A))
    # print('B = ', B, id(B))
    print('C = ', C, id(C))
    # print('C[0]', C[0], id(C[0]))

    D = copy.deepcopy(C)
    print('D = ', D, id(D))
    print('D[0]= ', id(D[0]), 'c[0] = ', id(C[0]), 'A[0] = ', id(A[0]))

    # 修改A的
    A[0] = 10
    print('A = ', A, id(A))
    print('D[0] = ', D[0], id(D[0]))


test2()

python中的切片拷贝,字典拷贝

def test():
    # 简单可变 深拷贝
    list1 = [1, 2, 3, 4, 56]
    print('list1 = ', list1, id(list1))
    # 切片拷贝
    list2 = list1[:]
    print('list = ', list, id(list))


def test2():
    A = [1, 2]
    B = [3, 4]
    C = (A, B)
    print('C = ', C, id(C))
    D = C[:]
    print('D = ', D, id(D))
    D[0][0] = 4


# 字典拷贝,浅拷贝
dict1 = {'age': [1, 2]}
print('dict1 = ', dict1, id(dict1))
dict2 = dict1.copy()
print('dict2 = ', dict2, id(dict2))
print('--'*10)
dict1['age'][0] = 10
print('dict1 = ', dict1, id(dict1))
print('dict2 = ', dict2, id(dict2))

关于python的拷贝就这么多

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页