鱼C论坛

 找回密码
 立即注册
查看: 2896|回复: 0

[学习笔记] python列表删除元素之del,pop()和remove()

[复制链接]
发表于 2021-5-17 22:40:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
del函数
如果知道要删除元素在列表中的位置,可以使用del语句:
  1. list_1 = ['one', 'two', 'three']
  2. print(list_1)

  3. del list_1[0]
  4. print(list_1)
复制代码

根据索引,del语句删除了list_1列表中的第一个元素——'one'
  1. ['one', 'two', 'three']
  2. ['two', 'three']
复制代码

要想使用del删除列表中的任意元素,前提是知道其索引(位置)
pop()
pop()顾名思义——弹出,弹出列表末尾的元素,并且使用这个弹出的元素:
  1. list_1 = ['one', 'two', 'three']
  2. print(list_1)

  3. pop_list_1 = list_1.pop()
  4. print(pop_list_1)
  5. print(list_1)
复制代码

这里使用pop()弹出了list_1列表的最后一个元素'three',并且把'three'赋值给了pop_list_1
  1. ['one', 'two', 'three']
  2. three
  3. ['one', 'two']
复制代码

当然,pop(索引)也可以弹出列表中的任意元素,前提是知道该元素的索引:
  1. list_1 = ['one', 'two', 'three']
  2. print(list_1)

  3. pop_list_1 = list_1.pop(1)
  4. print(pop_list_1)
  5. print(list_1)
复制代码

如del一般,这里弹出了列表的第二个元素(索引为1)
  1. ['one', 'two', 'three']
  2. two
  3. ['one', 'three']
复制代码

remove()
有时候我们不知道元素的索引的时候,但是知道要删除的这个元素是什么,那我们就可以用remove()这个方法
  1. list_1 = ['one', 'two', 'three']
  2. print(list_1)

  3. list_1.remove('two')
  4. print(list_1)
复制代码

此时我们知道了要删除的元素是'two',那么我们用remove()得:
  1. ['one', 'two', 'three']
  2. ['one', 'three']
复制代码

当然,和pop一样,被删除的元素我们依然可以使用:
  1. list_1 = ['one', 'two', 'three']
  2. print(list_1)

  3. remove_1 = 'two'
  4. list_1.remove(remove_1)
  5. print(list_1)

  6. print(remove_1.title())
复制代码

我们先把要删除的元素'two'存储在remove_1中,然后再用remove()方法把remove_1中存储的值删除,但是元素'two'依然存储在变量remove_1中
  1. ['one', 'two', 'three']
  2. ['one', 'three']
  3. Two
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-7 21:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表