• python的浅拷贝与深拷贝的区别


    一、赋值

    alist = ["a","b","c",[5,6],10]
    aa = alist
    alist.append("yu")
    aa.append("iop")
    alist[3].append(99)
    alist[3].append("test")
    print(alist)
    print(aa)

    执行结果如下:

    ['a', 'b', 'c', [5, 6, 99, 'test'], 10, 'yu', 'iop']
    ['a', 'b', 'c', [5, 6, 99, 'test'], 10, 'yu', 'iop']

    赋值说明是2个变量之间数据的互相传递,修改任何一变量的值,都会对另一变量值进行影响

    二、浅拷贝,copy()

    import copy

    #浅拷贝,没有拷贝元素中的内部元素,内部元素有改变就会相互影响

    blist = ["a","b","c",[5,6],10]
    bb = copy.copy(blist)
    blist.append("haha")
    bb.append(89)

    blist[3].append("qe")
    bb[3].append(99)

    print(blist)
    print(bb)

    执行结果:

    [90, 'b', 'c', [5, 6, 'qe', 99], 10, 'haha']#blist追加的‘haha’,并没有在bb的值中,对内部元素blist[3]添加‘qe’,会作用到bb的bb[3]内部元素中
    ['a', 'b', 'c', [5, 6, 'qe', 99], 10, 89]#bb追加的89,并没有在blist的值中,对内部元素bb[3]添99,会作用到blist的blist[3]内部元素中

    三、深拷贝

    import copy

    #深拷贝,拷贝后,各元素进行改变互不影响,包括子元素
    clist = ["a","b","c",[5,6],10]
    cc = copy.deepcopy(clist)
    clist.append(90)
    cc.append(100)

    clist[3].append(11)
    cc[3].append(10)

    print(clist)
    print(cc)

    执行结果:

    ['a', 'b', 'c', [5, 6, 11], 10, 90]
    ['a', 'b', 'c', [5, 6, 10], 10, 100]

    深拷贝其实就是内、外元素全部被拷贝,深拷贝后,2个变量的值改变,不会相互影响

  • 相关阅读:
    Python Semaphore
    Python 互斥锁
    Python 递归锁
    Python GIL锁
    Python 线程调用
    进程与线程
    Python paramiko模块
    Python SocketServer模块
    MonoDevelop with Visual Studio to Linux and Mac OSX maintaining a single code base for all platforms.
    mime大全收集
  • 原文地址:https://www.cnblogs.com/banxiade/p/12470241.html
Copyright © 2020-2023  润新知