zoukankan      html  css  js  c++  java
  • python之深浅拷贝

    1.=的意义

      s1= s2       将s2的值赋值给s1    id(s1) = id(s2)

    2.浅拷贝copy

      只拷贝第一层,拷贝表面

      id(s1) !=  id(s2)

      2.1 

    lst1 = ["元素1", "元素2", "元素3", "元素4"]
    lst2 = lst1.copy()  # 拷贝, 可以帮我们创建新的对象,和原来长的一模一样, 浅拷贝
    
    print(id(lst1))
    print(id(lst2))   # id(lst1)  !=id(lst2)
    
    lst1.append("元素5")
    print(lst1)
    print(lst2)   #lst1 和 lst2  输出内容不一致    lst1中有元素5,lst2中没有元素5
     lst1 = ["元素1", "元素2", "元素3", "元素4", ["元素5", "元素6", "元素7"]]
     lst2 = lst1.copy() # 浅拷贝. 只拷贝第一层内容
    
     print(id(lst1))
     print(id(lst2))
    
     print(lst1)
     print(lst2)
    
     lst1[4].append("元素8")
     print(lst1)
     print(lst2)  #lst1和lst2中内容一致

    3.深拷贝

      对象内部的所有内容都要复制一份

      需要引入copy模块

     lst1 = ["元素1", "元素2", "元素3", "元素4", ["元素5", "元素6", "元素7"]]
     lst2 = copy.deepcopy(lst1)  # 深拷贝: 对象内部的所有内容都要复制一份.
    
     print(id(lst1))
     print(id(lst2))
    
     print(lst1)
     print(lst2)
    
     lst1[4].append("葫芦娃")
     print(lst1)
     print(lst2)   #lst1 和lst2 输入内容不一致
  • 相关阅读:
    BZOJ 3330 分数
    FR #11题解
    BZOJ 1857 传送带
    BZOJ 4757 Building a Tall Barn
    FR #10题解
    BZOJ 4393 Fruit Feast
    BZOJ 3126 Photo
    BZOJ 1312 Hard Life
    BZOJ 2039 employ人员雇佣
    Count SIN Numbers
  • 原文地址:https://www.cnblogs.com/l1222514/p/13917239.html
Copyright © 2011-2022 走看看