zoukankan      html  css  js  c++  java
  • Python 字典一个易犯的错误

    一个易犯的错误,关于 Python 的传值(对于不可变量) 和 传引用(对于可变量),浅拷贝和深拷贝。废话不多说,看例子,

    直接改变可变字典值,失败,

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> dic[0]
    []
    >>> dic[0].append(123)
    >>> dic
    {0: [123], 1: [123], 2: [123], 3: [123], 4: [123]}
    >>> 

    间接改变可变字典值,失败。

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> v = dic[0]
    >>> v
    []
    >>> v.append(123)
    >>> v
    [123]
    >>> dic
    {0: [123], 1: [123], 2: [123], 3: [123], 4: [123]}

    切片浅拷贝,对于非嵌套可变字典值,赋单值,成功,

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> v = dic[0][:]
    >>> v
    []
    >>> v.append(123)
    >>> v
    [123]
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> 
    >>> dic[0] = v
    >>> dic
    {0: [123], 1: [], 2: [], 3: [], 4: []}

    切片浅拷贝,对于非嵌套可变字典值,赋可变列表,成功,

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> v = dic[0][:]
    >>> v.append([1, 2, 3])
    >>> v
    [[1, 2, 3]]
    >>> 
    >>> dic[0] = v
    >>> dic
    {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []}

    copy.copy 浅拷贝,成功,

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> 
    >>> v = copy.copy(dic[0])   # shallow copy
    >>> v
    []
    >>> v.append([1, 2, 3])
    >>> v
    [[1, 2, 3]]
    >>> 
    >>> dic[0] = v
    >>> dic
    {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []}
    >>> 

    copy.deepcopy 深拷贝,成功,这个最靠谱。

    >>> dic = dict.fromkeys(range(5), [])
    >>> dic
    {0: [], 1: [], 2: [], 3: [], 4: []}
    >>> 
    >>> v = copy.deepcopy(dic[0])
    >>> v
    []
    >>> v.append([1, 2, 3])
    >>> v
    [[1, 2, 3]]
    >>> 
    >>> dic[0] = v
    >>> dic
    {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []}
    >>> 

    完。

  • 相关阅读:
    关于springMVC转换json出现的异常
    jQuery实现,动态自动定位弹窗。JS分页,Ajax请求
    servlet为什么要配置web.xml
    Jmeter系列(4)- Jmeter 脚本录制
    后缀数组模板
    NOIP2016 玩脱记
    TERSUS无代码开发(笔记21)-流程执行顺序思考(转载)
    ===>===>===>特色思TERSUS常用功能整理
    TERSUS无代码开发(笔记20)-本地开发测试mysql数据库连接
    TERSUS无代码开发(笔记19)-mysql-connector-java-5.-bin.jar下载方法
  • 原文地址:https://www.cnblogs.com/gaowengang/p/8039886.html
Copyright © 2011-2022 走看看