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

    举例说明:

    # 引入copy模块
    import copy
    lst1 = [1, 2, 3, ["a", "b"]]
    # 赋值操作
    lst2 = lst1
    
    # 切片操作,会产生新的列表-浅拷贝
    lst3 = lst1[:]
    lst4 = lst1.copy()
    lst5 = copy.deepcopy(lst1)
    
    lst1.append(4)
    lst1[3].append("c")
    print(lst1)
    print(lst2)
    print(lst3)
    print(lst4)
    print(lst5)
    print(id(lst1))
    print(id(lst2))
    print(id(lst3))
    print(id(lst4))
    print(id(lst5))
    # 浅拷贝后嵌套列表的内存地址一致
    print(id(lst1[3]))
    print(id(lst4[3]))
    # 深拷贝后嵌套列表的内存地址一致
    print(id(lst1[3]))
    print(id(lst5[3]))

    运行结果:

    [1, 2, 3, ['a', 'b', 'c'], 4]
    [1, 2, 3, ['a', 'b', 'c'], 4]
    [1, 2, 3, ['a', 'b', 'c']]
    [1, 2, 3, ['a', 'b', 'c']]
    [1, 2, 3, ['a', 'b']]
    2251874503176
    2251874503176
    2251875870472
    2251875870408
    2251875870344
    2251874503880
    2251874503880
    2251874503880
    2251875870280

    总结:

    # 1. 赋值操作. 没有创建新对象
    # 2. 浅拷贝. 只拷贝第一层内容. [:]   copy()
    # 3. 深拷贝. 把这个对象内部的内容全部拷贝一份. 引入copy模块. deepcopy()
  • 相关阅读:
    2012暑期川西旅游之第六天(四姑娘山达维夹金山邛崃青城山)
    实现元素拖拽
    asp.net学习资源
    080402 晴れ
    送给Rain的文章
    两天后见
    若水三千
    关于下一代的教育
    20080408 大雨
    Missing You
  • 原文地址:https://www.cnblogs.com/benben-wu/p/13203211.html
Copyright © 2011-2022 走看看