python 列表元素的删除
使用del命令删除列表中的指定位置上的元素。
>>>a_list=[3,5,7,9,11]
>>>dela_list[1]
>>>a_list
[3,7,9,11]
使用列表的pop()方法删除并返回指定位置(默认为最后一个)上的元素,如果给定的索引超出了列表的范围则抛出异常。
>>>a_list=list((3,5,7,9,11))
>>>a_list.pop()
11
>>>a_list
[3,5,7,9]
>>>a_list.pop(1)
5
>>>a_list
[3,7,9]
使用列表对象的remove()方法删除首次出现的指定元素,如果列表中不存在要删除的元素,则抛出异常。
>>>a_list=[3,5,7,9,7,11]
>>>a_list.remove(7)
>>>a_list
[3,5,9,7,11]
代码编写好后必须要经过反复测试,不能满足于几次测试结果正确。例如,下面的代码成功地删除了列表中的重复元素,执行结果是完全正确的。
>>>x=[1,2,1,2,1,2,1,2,1]
>>>foriinx:
ifi==1:
x.remove(i)
>>>x
[2,2,2,2]
然而,上面这段代码的逻辑是错误的。同样的代码,仅仅是所处理的数据发生了一点变化,然而当循环结束后却发现并没有把所有的“1”都删除,只是删除了一部分。
>>>x=[1,2,1,2,1,1,1]
>>>foriinx:
ifi==1:
x.remove(i)
>>>x
[2,2,1]
两组数据的本质区别在于,第一组数据中没有连续的“1”,而第二组数据中存在连续的“1”。出现这个问题的原因是列表的自动内存管理功能。
在删除列表元素时,Python会自动对列表内存进行收缩并移动列表元素以保证所有元素之间没有空隙,增加列表元素时也会自动扩展内存并对元素进行移动以保证元素之间没有空隙。每当插入或删除一个元素之后,该元素位置后面所有元素的索引就都改变了。
正确的代码:
>>>x=[1,2,1,2,1,1,1]
>>>foriinx[::]:#切片
ifi==1:
x.remove(i)
或者:
>>>x=[1,2,1,2,1,1,1]
>>>foriinrange(len(x)-1,-1,-1):#从后往前删
ifx[i]==1:
delx[i]
以上内容为大家介绍了python列表元素的删除,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






