Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0107
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在:
- 个人网站: `https://oeasy.org`
- 蓝桥云课: `https://www.lanqiao.cn/courses/3584`
- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
- Gitee: `https://gitee.com/overmind1980/oeasypython`
---- 配套视频
- 上次研究的是del 删除
- 可以 删除列表项
- 也可以 删除切片
- 就像择菜一样
- 择出去的菜 搁
哪儿了呢?🤔
- 英雄列表
- 刘关张
hero_list = ["刘备", "关羽", "张飞"]
print(hero_list)
del hero_list[1:2]
print(hero_list)
- 帧栈(Frame)上 只能看见 hero_list
- hero_list 存的是 引用的地址(id)
- https://pythontutor.com/render.html#mode=display
-
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会相互影响?
- 去看看 具体地址
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
- 可以得到 对象
引用次数
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
不同- 对应的空间 也
不同
- 对应的空间 也
- 还有 啥方法 可以
不影响原列表 吗?
- 使用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这个单词
- 源于 中世纪时候
- 手抄本
- 影响到 后来的
- 复印机
- 胶片时代
- 表示胶片的拷贝
- 制片公司的产品 是 拷贝
- 到了 电脑时代
- 复制文件的命令
- 就是c(o)p(y)
- copy函数 可以制作
副本(copy)
- 列表 赋值运算 两种形式
- 将列表 直接 赋值
- 造成两个列表指向同一个对象
- 一改全改
- 将 列表副本 赋给 变量
- 这两个列表变量指向不同的对象
- 互不影响
- 将列表 直接 赋值
clist1 = list("oeasy")
clist2 = clist1
clist2 = clist1.copy()
- 列表 能相加 吗?🤔
lst1 + lst2
- 下次再说 👋
- 配套视频
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。

















