python实现删除列表中某个元素的3种方法

yipeiwu_com6年前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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python version 2.7 required, which was not found in the registry

Python version 2.7 required, which was not found in the registry

安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the registry。 如图: 大意是说找不到...

python线程的几种创建方式详解

Python3 线程中常用的两个模块为: _thread threading(推荐使用) 使用Thread类创建 import threading from time...

深入浅析python定时杀进程

之前写了个python脚本用selenium+phantomjs爬新帖子,在循环拉取页面的过程中,phantomjs总是block住,使用WebDriverWait设置最长等待时间无效。...

解决python3中自定义wsgi函数,make_server函数报错的问题

#coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ, start_...

Python 中urls.py:URL dispatcher(路由配置文件)详解

Python 中urls.py:URL dispatcher(路由配置文件)详解

urls.py:URL dispatcher(路由配置文件) URL配置(URLconf)就像是Django所支撑网站的目录。它的本质是URL模式以及要为该URL模式调用的视图函数之间的...