首页 技术 正文
技术 2022年11月14日
0 收藏 446 点赞 4,686 浏览 956 个字

一、从列表中删除元素

  1. 使用del 语句删除。
books = ['Pride and Prejudice','Jane Eyre','The Catcher in the Rye']
print(books)del books[0]
print(books)

console(控制台):

Python中的列表(2)

可以看到,列表中的第一个元素确实被删除了。需要注意的是这种删除方式为永久删除即删除之后就再也无法访问它了。

  2.使用pop()方法删除元素

books = ['Pride and Prejudice','Jane Eyre','The Catcher in the Rye']
print(books)book = books.pop()
print(books)print(book)

console(控制台):

Python中的列表(2)

pop()方法,理解为弹出元素更为恰当,它将列表中的元素弹出(此时列表中将不会出现这个元素)且可以用一个变量来接收,以便后续使用它。

pop()方法中可以传入一个参数,用以弹出指定索引处的元素,注意指定的索引 不要超过列表的最大索引,不然会出现索引越界错误。

  3.根据值删除元素

  有时候我们并不知道我们想删除的值处于什么位置,如果知道要删除元素的值,我们可以使用 remove() 方法。

  

books = ['Pride and Prejudice','Jane Eyre','The Catcher in the Rye']
print(books)books.remove('Jane Eyre')
print(books)

console(控制台):

Python中的列表(2)

这种方式删除列表中的元素,再删除之后也能继续使用它的值,用一个变量来定义要删除的值,再用列表调用remove方法,然后将此变量传入,即可删除列表中指定的元素。

books = [‘Pride and Prejudice’,’Jane Eyre’,’The Catcher in the Rye’]
print(books)

del_element = ‘Jane Eyre’

books.remove(del_element)
print(books)
print(del_element)

console(控制台):

Python中的列表(2)

可以看到和上面是一样的结果,而且还能打印出删除的元素以便后续使用。

tips:remove() 方法只能删除第一个指定的值,如果要删除全部指定的值,需要搭配循环来使用。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,991
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,505
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,349
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,134
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,766
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,844