zoukankan      html  css  js  c++  java
  • 深浅copy

     1 #浅copy,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址
     2 list1 = [1,2,[3,4]]
     3 list2 = list1.copy()
     4 print(list1,id(list1))
     5 print(list2,id(list2))
     6 
     7 list1[0]=3
     8 print(list1,id(list1),id(list1[2]))
     9 print(list2,id(list2),id(list2[2]))
    10 
    11 list1[2][0] = 5
    12 print(list1,id(list1),id(list1[2]))
    13 print(list2,id(list2),id(list2[2]))
    14 
    15 #深copy,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变
    16 import copy
    17 list1 = [1,2,[3,4]]
    18 list2 = copy.deepcopy(list1)
    19 
    20 print(list1,id(list1),id(list1[2]))
    21 print(list2,id(list2),id(list2[2]))
    22 
    23 list1[0] = 3
    24 print(list1,id(list1),id(list1[2]))
    25 print(list2,id(list2),id(list2[2]))
    26 
    27 list1[2][0] = 5
    28 print(list1,id(list1),id(list1[2]))
    29 print(list2,id(list2),id(list2[2]))
    [1, 2, [3, 4]] 2635642502984
    [1, 2, [3, 4]] 2635643714248
    [3, 2, [3, 4]] 2635642502984 2635643712648
    [1, 2, [3, 4]] 2635643714248 2635643712648
    [3, 2, [5, 4]] 2635642502984 2635643712648
    [1, 2, [5, 4]] 2635643714248 2635643712648
    [1, 2, [3, 4]] 2635643712520 2635643713288
    [1, 2, [3, 4]] 2635642502984 2635643719880
    [3, 2, [3, 4]] 2635643712520 2635643713288
    [1, 2, [3, 4]] 2635642502984 2635643719880
    [3, 2, [5, 4]] 2635643712520 2635643713288
    [1, 2, [3, 4]] 2635642502984 2635643719880
    
    Process finished with exit code 0
    结果
  • 相关阅读:
    LeetCode-Read N Characters Given Read4 II
    LeetCode-One Edit Distance
    LeetCode-Palindrome Permutation II
    LeetCode- Longest Absolute File Path
    LeetCode-Strobogrammatic Number II
    LeetCode-Strobogrammatic Number
    LeetCode-Flatten 2D Vector
    LeetCode-Shortest Word Distance III
    LeetCode-Shortest Word Distance II
    Cookie/Session
  • 原文地址:https://www.cnblogs.com/xiaodebing/p/9535166.html
Copyright © 2011-2022 走看看