zoukankan      html  css  js  c++  java
  • Python3的深拷贝和浅拷贝

    a = 1
    b = a
    a = 2
    print(a, b)
    print(id(a), id(b))
    """
    运行结果
    2 1
    1445293568 1445293536
    """
    
    # 列表直接复赋值给列表不属于拷贝, 只是内存地址的引用
    list1 = ["a", "b", "c"]
    list2 = list1
    list1.append("d")
    print(list1, list2)
    print(id(list1), id(list2))
    """
    运行结果
    ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
    1947385383176 1947385383176
    """
    
    # 浅拷贝
    list1 = ["a", "b", "c"]
    list2 = list1.copy()
    list1.append("d")
    print(list1, list2)
    print(id(list1), id(list2))
    """ 
    运行结果:
    ['a', 'b', 'c', 'd'] ['a', 'b', 'c']
    1553315383560 1553315556936
    """
    
    # 浅拷贝, 只会拷贝第一层, 第二层的内容不会拷贝
    list1 = ["a", "b", "c", [1, 2, 3]]
    list2 = list1.copy()
    list1[3].append(4)
    print(list1, list2)
    print(id(list1), id(list2))
    """
    运行结果
    ['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3, 4]]
    1386655149640 1386655185672
    """
    
    # 深拷贝
    import copy  
    list1 = ["a", "b", "c", [1, 2, 3]]
    list2 = copy.deepcopy(list1)
    list1[3].append(4)
    print(list1, list2)
    print(id(list1), id(list2))
    """
    运行结果
    ['a', 'b', 'c', [1, 2, 3, 4]] ['a', 'b', 'c', [1, 2, 3]]
    1452762592904 1452762606664
    """
    
  • 相关阅读:
    chroot 与 jail
    3-07. 求前缀表达式的值(25) (ZJU_PAT数学)
    一种监控全部账户登陆及操作命令的方法
    怎样设计接口?
    UVA10869
    网络直播电视之M3U8解析篇 (下)
    LCD显示--Ht1621b芯片显示屏驱动
    混淆
    android 调试
    eclipse+webservice开发实例
  • 原文地址:https://www.cnblogs.com/hellomrr/p/10705072.html
Copyright © 2011-2022 走看看