本文摘自php中文网,作者青灯夜游,侵删。
python删除列表中元素的方法:1、使用remove()删除单个元素,该函数可以删除列表中某个值的第一个匹配项;2、使用pop()删除单个或多个元素,该函数根据索引来删除元素,并返回该元素的值;3、使用del关键字根据索引来删除元素。

本教程操作环境:windows7系统、python3版,DELL G3电脑
python中关于删除list中的某个元素,一般有三种方法:remove、pop、del:
1.remove: 删除单个元素,删除首个符合条件的元素,按值删除
举例说明:
1 2 3 | >>> str=[1,2,3,4,5,2,6]
>>> str.remove(2)
>>> str
|
输出
2.pop: 删除单个或多个元素,按位删除(根据索引删除)
1 2 3 4 | >>> str=[0,1,2,3,4,5,6]
>>> str.pop(1) #pop删除时会返回被删除的元素
>>> str
[0, 2, 3, 4, 5, 6]
|
1 2 3 4 5 | >>> str2=[ 'abc' , 'bcd' , 'dce' ]
>>> str2.pop(2)
'dce'
>>> str2
[ 'abc' , 'bcd' ]
|
3.del:它是根据索引(元素所在位置)来删除
举例说明:
1 2 3 4 | >>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str
[1, 3, 4, 5, 2, 6]
|
1 2 3 4 | >>> str2=[ 'abc' , 'bcd' , 'dce' ]
>>> del str2[1]
>>> str2
[ 'abc' , 'dce' ]
|
除此之外,del还可以删除指定范围内的值。
1 2 3 4 | >>> str=[0,1,2,3,4,5,6]
>>> del str[2:4] #删除从第2个元素开始,到第4个为止的元素(但是不包括尾部元素)
>>> str
[0, 1, 4, 5, 6]
|
del 也可以删除整个数据对象(列表、集合等)
1 2 3 4 5 6 7 | >>> str=[0,1,2,3,4,5,6]
>>> del str
>>> str #删除后,找不到对象
Traceback (most recent call last):
File "<pyshell#27>" , line 1, in <module>
str
NameError: name 'str' is not defined
|
注意:del是删除引用(变量)而不是删除对象(数据),对象由自动垃圾回收机制(GC)删除。
补充: 删除元素的变相方法
1 2 3 4 5 | s1 = (1, 2, 3, 4, 5, 6)
s2 = (2, 3, 5)
s3 = [] for i in s1: if i not in s2:
s3.append(i) print ( 's1_1:' , s1)
s1 = s3print( 's2:' , s2) print ( 's3:' , s3) print ( 's1_2:' , s1)
|
相关推荐:Python3视频教程
以上就是python中怎么删除列表中的元素的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python的gil是什么?Python中gil的介绍
Python的线程join怎么用
Python能做什么科学计算
Python中的self多余吗
Python实现的根据文件名查找数据文件功能示例
怎么查看Python的安装路径?
Python的idle打不开怎么办
Python安装包里idle在哪
Python基础教程项目二之画幅好画
Python中argparse库的基本使用(示例)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python中怎么删除列表中的元素