oeasy玩python107_列表_拷贝赋值
列表_拷贝_copy_赋值_assignment
回忆
-
上次研究的是del 删除
-
可以 删除列表项
-
也可以 删除切片
-

-
就像择菜一样

-
择出去的菜 搁
哪儿了呢?🤔
地址
-
英雄列表
-
刘关张
-
hero_list = ["刘备", "关羽", "张飞"]
print(hero_list)
del hero_list[1:2]
print(hero_list)
-
帧栈(Frame)上 只能看见 hero_list
-
hero_list 存的是 引用的地址(id)
-

-
del 列表切片后
-
帧栈(Frame)上 还是 只能看见 hero_list
-
此时列表 还剩 2个列表项
-
堆对象空间(heap)上 释放了hero_list[1]内存
-
-
如果 切片 没被赋给任何对象
-
也就
消失了
-
-
怎么 存住 被删的切片 呢?
观察
-
把 被删的切片
-
赋给
新变量 呢?
-
hero_list = ["刘备", "关羽", "张飞"]
print(hero_list)
selected = hero_list[1:2]
del hero_list[1:2]
print(hero_list)
print(selected)
-
切完切片之后
-
将切片信息 赋给 一个新列表变量
-
这个切片就保留下来了
-

-
修改切片
-
会影响原始列表吗?
-
修改切片
-
新切片
-
有自己的空间
-
hero_list = ["刘备", "关羽", "张飞"]
print(hero_list)
selected = hero_list[1:2]
del hero_list[1:2]
selected.append("赵云")
print(hero_list)
print(selected)
-
对新切片对象的操作
-
不影响原来的切片
-

-
那如何 让列表 互相影响 呢?
互相影响
-
直接 用列表 给 新变量赋值
-
让clist1、clist2指向同一个地址空间
-
clist1 = list("oeasy")
clist2 = clist1
clist1.append("?")
clist2.append("!")

-
为啥clist1、clist2会相互影响?
id
-
去看看 具体地址
clist1 = list("oeasy")
print(clist1,id(clist1))
clist2 = clist1
print(clist2, id(clist2))
clist1.append("?")
clist2.append("!")
print(id(clist1) == id(clist2))
-
clist1、clist2 引用的是
-
同一个对象地址 -
所以
-
不论 谁append
-
都会append到 这个地址对应的列表 上
-
-

-
列表 被引用了
几次呢?
getrefcount
-
getrefcount
-
可以得到 对象
-
引用次数
-
import sys
clist1 = list("oeasy")
print(sys.getrefcount(clist1))
-
明明是 clist1
-
1个变量引用
-

-
为什么 显示
2个引用呢?
帮助手册
import sys
help(sys.getrefcount)
-
每次 getrefcount被调用时
-
增加 1个引用
-
所以显示2个
-

-
取消引用
-
被引用数 会减少 吗?
-
取消引用
clist2 = clist1
print(sys.getrefcount(clist1))
clist2 = []
print(sys.getrefcount(clist1))
del clist1
print(sys.getrefcount(clist1))
-
这时候 clist2引用 别的地址
-
那clist1 引用数 就会减1
-

-
clist1 和 clist2 引用
同一位置-
他俩 会
一改全改 -
有什么办法 不要
一改全改吗?
-
使用构造函数
-
新作一个列表
-
根据 nlist1
-
再
新造一个 nlist2
-
nlist1 = [1, 2, 3]
nlist2 = list(nlist1)
print(id(nlist1), id(nlist2))
-
id
不同-
对应的空间 也
不同
-

-
还有 啥方法 可以
不影响原列表 吗?
copy副本
-
使用list类的 copy方法
clist1 = list("oeasy")
clist2 = clist1.copy()
clist1.append("?")
clist2.append("!")
-
列表 和 列表的拷贝
-
引用不同的位置
-

-
这 两个列表 地址还相同 吗?
确保
clist1 = list("oeasy")
clist2 = clist1.copy()
print(id(clist1))
print(id(clist2))
-
id不同
-
copy后 就新分出 空间
-

-
给 原列表 做了个副本
copy
-
拷贝 就是
-
建立副本
-

-
copy这个单词
-
源于 中世纪时候
-
手抄本
-

-
影响到 后来的
-
复印机
-
拷贝
-
胶片时代
-
表示胶片的拷贝
-
制片公司的产品 是 拷贝
-

-
到了 电脑时代
-
复制文件的命令
-
就是c(o)p(y)
-

-
copy函数 可以制作
副本(copy)
总结🤔
-
列表 赋值运算 两种形式
-
将列表 直接 赋值
-
造成两个列表指向同一个对象
-
一改全改
-
-
将 列表副本 赋给 变量
-
这两个列表变量指向不同的对象
-
互不影响
-
-
clist1 = list("oeasy")
clist2 = clist1
clist2 = clist1.copy()

-
列表 能相加 吗?🤔
lst1 + lst2
-
下次再说 👋
891

被折叠的 条评论
为什么被折叠?



