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

yipeiwu_com7年前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 使用sys.stdin和fileinput读入标准输入的方法

1、使用sys.stdin 读取标准输入 [root@c6-ansible-20 script]# cat demo02.py #! /usr/bin/env python fro...

Python time模块详解(常用函数实例讲解,非常好)

Python time模块详解(常用函数实例讲解,非常好)

在开始之前,首先要说明这几点: 1.在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的ti...

Python中datetime常用时间处理方法

常用时间转换及处理函数: import datetime # 获取当前时间 d1 = datetime.datetime.now() print d1 # 当前时间加上半小时 d2...

Pytorch根据layers的name冻结训练方式

使用model.named_parameters()可以轻松搞定, model.cuda() # ######################################...

python操作mongodb根据_id查询数据的实现方法

本文实例讲述了python操作mongodb根据_id查询数据的实现方法。分享给大家供大家参考。具体分析如下: _id是mongodb自动生成的id,其类型为ObjectId,所以如果需...