• 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: []}
    >>> 

    完。

  • 相关阅读:
    ACwing(基础)--- 01背包和完全背包、多重背包问题
    Python --- 实战一
    Python --- 正则表达式
    Python --- 网络爬虫
    Python --- 异常处理
    Python --- 文件操作
    Python --- 模块
    Python --- 基础语法
    securecrt颜色设置
    Tomcat启动排查
  • 原文地址:https://www.cnblogs.com/gaowengang/p/8039886.html
Copyright © 2020-2023  润新知