python中删除某个元素的方法解析
作者:Python热爱者 时间:2021-02-02 00:05:40
这篇文章主要介绍了python中删除某个元素的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
python中关于删除list中的某个元素,一般有三种方法:remove、pop、del
1.remove: 删除单个元素,删除首个符合条件的元素,按值删除
举例说明:
>>> str=[1,2,3,4,5,2,6]
>>> str.remove(2)
>>> str
[1, 3, 4, 5, 2, 6]
2.pop: 删除单个或多个元素,按位删除(根据索引删除)
>>> str=[0,1,2,3,4,5,6]
>>> str.pop(1) #pop删除时会返回被删除的元素
>>> str
[0, 2, 3, 4, 5, 6]
>>> str2=['abc','bcd','dce']
>>> str2.pop(2)
'dce'
>>> str2
['abc', 'bcd']
3.del:它是根据索引(元素所在位置)来删除
举例说明:
>>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str
[1, 3, 4, 5, 2, 6]
>>> str2=['abc','bcd','dce']
>>> del str2[1]
>>> str2
['abc', 'dce']
除此之外,del还可以删除指定范围内的值。
>>> str=[0,1,2,3,4,5,6]
>>> del str[2:4] #删除从第2个元素开始,到第4个为止的元素(但是不包括尾部元素)
>>> str
[0, 1, 4, 5, 6]
del 也可以删除整个数据对象(列表、集合等)
>>> 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)删除。
补充: 删除元素的变相方法
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=s3
print 's2:',s2
print 's3:',s3
print 's1-2:',s1
来源:https://blog.51cto.com/14246112/2447752
标签:python,删除,元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何从ASP连接到Oracle Server?
2009-11-15 19:52:00
Python实现批量读取word中表格信息的方法
2023-03-25 19:02:05
python被修饰的函数消失问题解决(基于wraps函数)
2021-07-22 17:32:34
网页设计进阶之一 (步骤和大局观)
2008-08-23 10:39:00
Python (Win)readline和tab补全的安装方法
2021-07-30 16:04:46
![](https://img.aspxhome.com/file/2023/5/76965_0s.jpg)
Pycharm 2020年最新激活码(亲测有效)
2023-07-24 00:42:14
![](https://img.aspxhome.com/file/2023/6/59136_0s.png)
一起来学习Python的列表
2022-08-04 06:06:23
960 时代的终结
2011-01-11 19:24:00
![](https://img.aspxhome.com/file/UploadPic/20111/11/1294635311-31s.png)
Pygame实战之实现经典外星人游戏
2021-05-10 00:31:44
![](https://img.aspxhome.com/file/2023/3/90593_0s.gif)
一篇文章带你入门python之推导式
2022-02-05 08:29:35
javascript 函数调用的对象和方法
2010-07-02 12:25:00
python xlsxwriter创建excel图表的方法
2021-01-12 03:16:10
![](https://img.aspxhome.com/file/2023/0/89180_0s.jpg)
Discuz7 的提示效果如何实现
2010-01-13 13:10:00
![](https://img.aspxhome.com/file/UploadPic/20101/13/2010113131444838s.jpg)
详解go中的引用类型
2023-08-28 06:02:31
Python实现基于HTTP文件传输实例
2021-10-23 13:24:53
谈谈网页一屏有多大?
2007-12-21 12:28:00
![](https://img.aspxhome.com/file/UploadPic/200712/21/2007122112356981s.jpg)
Python hashlib加密模块常用方法解析
2022-03-11 05:20:05
python中kmeans聚类实现代码
2023-09-27 19:49:44
SQL Server修改标识列方法 如自增列的批量化修改
2012-06-06 19:42:35
错误 2812: 未能找到存储过程 'master.dbo.xp_fileexist'
2010-07-22 19:50:00