您现在的位置是:课程教程文章

python中列表怎么删除元素

2023-12-18 22:50课程教程文章 人已围观

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]

补充: 删除元素的变相方法

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中如何使用help()

下一篇:没有了

站点信息

  • 文章统计篇文章