zoukankan      html  css  js  c++  java
  • 拷贝、浅拷贝、深拷贝解答

    拷贝

    拷贝/浅拷贝/深拷贝都是针对可变类型数据而言的

    list1 = ["a","b","c","d","f",["e","f","g"]]
    list2 = list1
    
    list1[2] = "plf"
    list1[5][0] = "lt"
    
    print(list1)
    print(list2)
    
    '''
    ['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g']]
    ['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g']]
    
    '''
    
    
    '''
    	总结:  如果list2是 list1的拷贝,那么list1和list2公用一块内存空间,因此list1改变,list2也会随着改变!
    		
    '''
    


    浅拷贝

    import copy
    list1 = ["a","b","c","d","f",["e","f","g"]]
    list2 = copy.copy(list1)
    
    list1[2] = "plf"
    list1[5][0] = "lt"
    list1[5].append("xyz")
    
    print(list1)
    print(list2)
    
    
    
    '''
    ['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
    ['a', 'b', 'c', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
    
    '''
    
    
    
    '''
    	总结: 
    		1.  如果 list2 是 list1 的浅拷贝对象,则1内的不可变元素发生了改变,list2 不变;  
    		2.	如果 list1 内的可变元素发生了改变,则 list2 会跟着改变.
    
    '''
    


    深拷贝

    import copy
    
    list1 = ["a","b","c","d","f",["e","f","g"]]
    list2 = copy.deepcopy(list1)
    
    list1[2] = "plf"
    list1[5][0] = "lt"
    list1[5].append("xyz")
    
    print(list1)
    print(list2)
    
    
    '''
    ['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
    ['a', 'b', 'c', 'd', 'f', ['e', 'f', 'g']]
    '''
    
    
    
    '''
    	总结:
    		如果list2 是 list1 的深拷贝,那么list1 和list2 都是独立的个体,不存在任何关系
    
    '''
    

  • 相关阅读:
    Reactor Cooling(无源汇有上下界网络流)
    费用流——消圈算法
    中间数(二分)+单调队列
    使用ServerSocket建立聊天服务器(二)
    使用ServerSocket建立聊天服务器(一)
    ServerSocket的建立和使用
    Socket介绍
    使用HttpClient进行Post通信
    使用HttpClient进行Get通信
    使用Post进行Http通信
  • 原文地址:https://www.cnblogs.com/plf-Jack/p/10920216.html
Copyright © 2011-2022 走看看