• python标准库介绍——9 copy模块详解


    ==copy 模块==
    
    
    ``copy`` 模块包含两个函数, 用来拷贝对象, 如 [Example 1-64 #eg-1-64] 所示. 
    
    ``copy(object) => object`` 创建给定对象的 "浅/浅层(shallow)" 拷贝(copy). 这里 
    "浅/浅层(shallow)" 的意思是复制对象本身, 但当对象是一个容器 (container) 时, 
    它的成员仍然指向原来的成员对象. 
    
    ====Example 1-64. 使用 copy 模块复制对象====[eg-1-64]
    
    ```
    File: copy-example-1.py
    
    import copy
    
    a = [[1],[2],[3]]
    b = copy.copy(a)
    
    print "before", "=>"
    print a
    print b
    
    # modify original
    a[0][0] = 0
    a[1] = None
    
    print "after", "=>"
    print a
    print b
    
    *B*before =>
    [[1], [2], [3]]
    [[1], [2], [3]]
    after =>
    [[0], None, [3]]
    [[0], [2], [3]]*b*
    ```
    
    你也可以使用[:]语句 (完整切片) 来对列表进行浅层复制, 也可以使用 ``copy`` 方法复制字典. 
    
    相反地, ``deepcopy(object) => object`` 创建一个对象的深层拷贝(deepcopy), 
    如 [Example 1-65 #eg-1-65] 所示, 当对象为一个容器时, 所有的成员都被递归地复制了。 
    
    ====Example 1-65. 使用 copy 模块复制集合(Collections)====[eg-1-65]
    
    ```
    File: copy-example-2.py
    
    import copy
    
    a = [[1],[2],[3]]
    b = copy.deepcopy(a)
    
    print "before", "=>"
    print a
    print b
    
    # modify original
    a[0][0] = 0
    a[1] = None
    
    print "after", "=>"
    print a
    print b
    
    *B*before =>
    [[1], [2], [3]]
    [[1], [2], [3]]
    after =>
    [[0], None, [3]]
    [[1], [2], [3]]*b*
    ```
  • 相关阅读:
    CF 441E Valera and Number
    CodeForces 1111E. Tree
    CodeForces 1098F. Ж-function
    CodeForces 1098E. Fedya the Potter
    CodeForces 1098D. Eels
    CodeForces 1103E. Radix sum
    CodeForces 1103D. Professional layer
    CodeForces 1103C. Johnny Solving
    CodeForces 1107F. Vasya and Endless Credits
    Hackerrank: Week of Code 36
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/7748300.html
Copyright © 2020-2023  润新知