列表 - 切片 - slice - 删除
-
上次研究了
回环文-
绕圈读
-
文字
重叠反复
-
-
这些都是由 列表构成的
-
列表 还能怎么玩呢?🤔
-
-
可以根据切片
-
删除列表项 吗?🤔
-
回忆删除
python
-
进入游乐场
a
a = 1
a
del a
a
-
删了变量 就 找不到了
-
删除del
-
删除的是
-
变量名字
-
和具体存储空间之间的绑定关系
-
-
-
可以更明确地演示吗?
网站
a = 1
print(a)
del a
print("hello")
-
可以一步步观察程序执行的过程
-
https://pythontutor.com/render.html#mode=display
-
-
执行过程
-
对a声明并赋值之后
-
Global Frames
-
全局程序栈的
帧(frame)上 -
就有了 变量a
-
具体值 为 1
-
-
del a之后
-
全局程序栈的
帧(frame)上 -
变量a就消失了
-
-
-
列表中 的
列表项可以删 吗?
删除 列表项
nlist = list(range(5))
nlist
nlist[2]
del nlist[2]
nlist
-
效果
-
del后的列表 还在
原来的内存地址 吗?
确认id
-
使用id函数 观察地址
id(nlist)
del nlist[2]
id(nlist)
-
nlist 还是
原来的 地址-
但 里面的列表项
-
被删(del)了
-
-
list类 的 remove方法
-
也能 删除
-
两者有什么区别吗?
-
del 和 remove
-
建立字符列表clist
clist = list("oeasy")
clist
clist.remove("y")
clist
del clist[2]
clist
-
两者都可以删除
| remove | del | |
|---|---|---|
| 删除依据 | 具体列表项 | 索引序号 |
| 类型 | 列表类方法 | 关键字 |
| 删除范围 | 某个列表项 | 切片范围 |
-
怎么删除
切片呢?
删除过程
-
建立数字列表nlist
nlist = list(range(5))
nlist
nlist[1:3]
del nlist[1:3]
nlist
-
删除其中的切片
-
nlist[1:3]
-
-
就像 切鱼一样
-
把 中段切掉
-
首尾 对接
-
鱼
-
吃鱼看性格
-
第一筷子 选
-
月牙肉
-
鱼唇
-
-
-
这些部分 最好吃
-
显示出 从小受宠
-
可能 自我中心
-
-
我们来拾掇拾掇鱼
拾掇鱼
-
一条鱼切成三段
fish = ["head", "body", "tail"]
-
掐头
-
去尾
不要当间
-
删除支持步长么?
回忆步长
nlist = list(range(10))
nlist[3:6]
nlist[3:]
nlist[:6]
nlist[::1]
nlist[::2]
nlist[::3]
nlist[1::3]
nlist[2::3]
nlist[3::3]
nlist[3:9:3]
-
切片效果
步长删除
nlist = list(range(10))
nlist
nlist[2::2]
del nlist[2::2]
nlist
-
效果
-
del支持 步长
继续
-
在此基础上 再删除
nlist
nlist[::5]
del nlist[::5]
nlist
-
结果
-
字符串可以通过del删除切片吗?
字符串 删除切片
s = "oeasy"
s[1:3]
del s[1:3]
-
字符串 支持切片
-
但 不支持切片删除
-
-
怎么办呢?
绕道列表
-
字符串 不支持 del关键字
-
但是
列表支持 -
先把 字符串
转化为列表
-
s = "oeasy"
clist = list(s)
del clist[1:3]
clist
s = ""
for c in clist:s = s + cprint(s)
-
最后 再把 列表
转化回字符串-
直着 过不去
-
绕过去
-
-
https://pythontutor.com/render.html#mode=display
总结🤔
-
这次研究的是del 删除
-
可以 删除列表项
-
也可以 删除切片
-
-
就像择菜一样
-
择出去的菜 搁
哪儿了呢?🤔 -
下次再说 👋