Skip to content

Latest commit

 

History

History
230 lines (164 loc) · 4.01 KB

File metadata and controls

230 lines (164 loc) · 4.01 KB
Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0115
- 这是 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` 
---

列表_删除指定列表项_弹栈_pop

回忆

  • 配套视频
  • 上次我们了解了
    • 定点插入 insert
    • 相对原来的 追加append
  • 排好序之后
    • 想要 保持有序
    • 需要 insert
    • 定点 插入

图片描述

  • 可以 定点 删除吗?

定点删除

图片描述

  • 这方法
    • 按照索引 删除列表项
    • 名字 叫 pop

图片描述

  • pop 啥意思?

pop

  • pop 最开始时拟声词

图片描述

  • 后来也指爆发的东西
    • 或者流行的东西
    • popular

图片描述

  • pop怎么用呢?

删除

  • 指定删除第 2 个列表项
    • 第2个列表项为 2
nl = list(range(0, 5))
print(nl)
nl.pop(2)
print(nl)
  • pop方法
    • 返回第2个列表项
    • 列表项 为 2
    • 删除成功

图片描述

  • 这个方法 和 del关键字
    • 不是一样吗?

del

  • 删除索引为2的列表项
nl = list(range(0, 5))
print(nl)
del nl[2]
print(nl)
  • 可以删除

图片描述

  • 甚至还可以切片删除
del nl[-2:]
nl
  • 切片删除成功

图片描述

  • 有了 del 为啥还要有pop呢?

提问

图片描述

  • 类型不同
    • del 是
      • 通用关键字
      • 不止删除 列表项和切片
    • pop 是
      • list类 的方法

默认参数

  • 如果pop方法 没有参数
    • 如何呢?
nl = list(range(0, 5))
print(nl)
nl.pop()
print(nl)
  • 默认参数 弹的是
    • 最后一个
    • default last

图片描述

  • 为啥是最后一个

pop弹栈

help(list.pop)
  • pop的 index参数
    • 默认值 是 -1
  • -1 不就是
    • 最后一项 的 索引 吗?!

图片描述

  • 这 效果 叫
    • 弹栈
    • pop the stack

列表的pop

nl = list(range(3))
nl
nl.pop()
nl
nl.pop()
nl
nl.pop()
nl
nl.pop()
nl
  • index 默认值 是 -1
    • 默认删 的是 最后一个

图片描述

  • pop 和 remove
    • 什么区别呢?

返回值

cl = list("oeasy")
cl
cl.pop(2)
cl
cl.remove("o")
cl
  • pop 按照位置删
    • 并返回列表项的值

图片描述

  • remove 按照值删
    • 没有返回值
  • remove 和 pop
    • 都是 list类的 成员方法

删除的总结

方法/关键字 功能描述
remove() 删首个匹配指定值的项
pop() 删 指定索引
del 删 指定索引/切片范围
clear() 删列表所有项
  • 现在list 所有的方法 我们都见过了

图片描述

list方法总结

图片描述

  • 去总结吧

总结

  • 这次我们了解了
    1. 按索引 删除 pop
      • 按值删除 remove
    2. 按索引 定点插入 insert

图片描述

  • 排好序 之后 可以打乱顺序吗?
  • 下次再说 👋
  • 配套视频

  • 本文来自 oeasy Python 系统教程。
  • 想完整、扎实学 Python,
  • 搜索 oeasy 即可。