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

    1. 列表和字典,直接赋值,都是浅拷贝,即赋值双方指向同一地址,因为 Python 对可变对象按引用传递。

    >>> a = [1, 2, 3]
    >>> b = a
    >>> b
    [1, 2, 3]
    >>> a[0] = 'apple'
    >>> a
    ['apple', 2, 3]
    >>> b
    ['apple', 2, 3]
    >>> 
    >>> 
    >>> dic = {'a': 'apple', 'b': 'banbana'}
    >>> dic2 = dic
    >>> dic2
    {'a': 'apple', 'b': 'banbana'}
    >>> dic['b'] = 'blueberry'
    >>> dic
    {'a': 'apple', 'b': 'blueberry'}
    >>> dic2
    {'a': 'apple', 'b': 'blueberry'}

    2. 对非嵌套的列表,使用完全切片[:], 工厂函数 list(),或者 copy.copy() 都是深拷贝。

    >>> a = [1, 2, 3]
    >>> b = list(a)
    >>> c = a[:]
    >>> import copy
    >>> d = copy.copy(a)
    >>> 
    >>> a[0] = 'apple'
    >>> a
    ['apple', 2, 3]
    >>> b
    [1, 2, 3]
    >>> c
    [1, 2, 3]
    >>> d
    [1, 2, 3]

    3. 对于非嵌套的字典,使用工厂函数 dict(),或者 copy.copy() 都是深拷贝。

    >>> dic = {'a': 'apple', 'b': 'banana'}
    >>> dic2 = dict(dic)
    >>> import copy
    >>> dic3 = copy.copy(dic)
    >>> 
    >>> dic['b'] = 'blueberry'
    >>> dic
    {'a': 'apple', 'b': 'blueberry'}
    >>> dic2
    {'a': 'apple', 'b': 'banana'}
    >>> dic3
    {'a': 'apple', 'b': 'banana'}

    4. 对于嵌套的列表,嵌套的字典,只能使用 copy.deepcopy() 实现深拷贝。

    >>> import copy
    >>> 
    >>> a = [1, 2, ['apple']]
    >>> b = copy.deepcopy(a)
    >>> a[2][0] = 'watermelon'
    >>> a
    [1, 2, ['watermelon']]
    >>> b
    [1, 2, ['apple']]
    >>> 
    >>> 
    >>> dic = {'a': 'apple', 'b': {'b1': 'banana', 'b2': 'blueberry'}}
    >>> dic2 = copy.deepcopy(dic)
    >>> dic['b']['b1'] = 'bukeneng'
    >>> dic
    {'a': 'apple', 'b': {'b1': 'bukeneng', 'b2': 'blueberry'}}
    >>> dic2
    {'a': 'apple', 'b': {'b1': 'banana', 'b2': 'blueberry'}}

    5. 对于嵌套可变对象的元组,只有 copy.deepcopy() 实现深拷贝。

    >>> import copy
    >>>
    >>> t = (1, 2, ['apple']) >>> t2 = t >>> t3 = tuple(t) >>> t4 = copy.copy(t) >>> t5 = copy.deepcopy(t) >>> >>> t[2][0] = 'watermelon' >>> t (1, 2, ['watermelon']) >>> t2 (1, 2, ['watermelon']) >>> t3 (1, 2, ['watermelon']) >>> t4 (1, 2, ['watermelon']) >>> t5 (1, 2, ['apple'])

    完。

  • 相关阅读:
    MYSQL中delete删除多表数据
    Docker核心实现技术 (命名空间 & 控制组 & 联合文件系统 & Linux网络虚拟化支持)
    Using VNCserver + GUI application + Virtual Display in Docker container
    Xvfb or X virtual framebuffer
    noVNC: HTML5 VNC Client
    Docker GUI调研
    Fedora 26
    SIM卡将逐渐消失,eSIM卡的风口已来?
    Capturing Wireless LAN Packets in Monitor Mode with iw
    connect two WiFi simultaneously
  • 原文地址:https://www.cnblogs.com/gaowengang/p/7855941.html
Copyright © 2011-2022 走看看