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设计】。

相关文章

matplotlib.pyplot画图并导出保存的实例

我就废话不多说了,直接上代码吧! import pandas as pd import numpy as np import matplotlib.pyplot as plt fig...

python与caffe改变通道顺序的方法

把通道放在前面: image = cv2.imread(path + file) image = cv2.resize(image, (48, 48), interpolation...

python多行字符串拼接使用小括号的方法

多行字符串拼接使用小括号 s = ('select *' 'from atable' 'where id=888') print s, type(s) #输出 select...

python解释器spython使用及原理解析

python解释器spython使用及原理解析

简介 出于个人爱好和某种需求,我再16年对python的解释器产生了浓厚兴趣,并且下定决心重新实现一个版本。我个人再游戏服务器开发中,对c++嵌入lua和python都有着丰富应用经验...

Python 实现异步调用函数的示例讲解

async_call.py #coding:utf-8 from threading import Thread def async_call(fn): def wrapper...