Python对于列表的del, remove, pop操作的区别
来源:互联网 发布:数据库视频教程 编辑:程序博客网 时间:2024/05/16 07:53
首先,remove 是删除首个符合条件的元素。并不是删除特定的索引。如下例:
而对于 del 来说,它是根据索引(元素所在位置)来删除的,如下例:
- >>> a = [0, 2, 2, 3]
- >>> a.remove(2)
- >>> a
- [0, 2, 3]
第1个元素为a[0] --是以0开始计数的。则a[1]是指第2个元素,即里面的值2.
- >>> a = [3, 2, 2, 1]
- >>> del a[1]
- [3, 2, 1]
del还可以删除指定范围内的值
a = [3,2,2,1]
del a[1,3]
print a
结果[3]
del还可以删除整个列表
del a
pop返回的是你弹出的那个数值。
所以使用时要根据你的具体需求选用合适的方法
- >>> a = [4, 3, 5]
- >>> a.pop(1)
- 3
- >>> a
- [4, 5]
另外它们如果出错,出错模式也是不一样的。注意看下面区别:
注:本文引自stackoverflow Q11520492
- >>> a = [4, 5, 6]
- >>> a.remove(7)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- ValueError: list.remove(x): x not in list
- >>> del a[7]
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- IndexError: list assignment index out of range
- >>> a.pop(7)
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- IndexError: pop index out of range
http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html
0 0
- Python对于列表的del, remove, pop操作的区别
- Python对于列表的del, remove, pop操作的区别
- python 数组的del ,remove,pop区别
- python 3.x中列表中元素删除del、remove、pop的用法及区别
- python:remove,pop和del方法的区别
- python-pop,del,remove
- python中列表的pop、remove、-1
- 1007 Python之List中remove,pop,del区别分析
- python remove和del的区别,python 循环删除元素
- Python append , pop, del 和 remove 基础知识篇
- Python基础学习--删除元素(remove,del,pop)
- Python的del语句与列表
- python 的 remove 和 pop 好奇怪
- Python列表类型的内建函数使用实例(insert、remove、index、pop等)
- Python中append()和extend()的区别,pop()和remove()的区别
- Python list del remove
- 自己使用python的列表del函数一个思维误区
- Python对于文件的操作
- Elasticsearch——Query DSL
- Spark PG1. 概述,连接Spark, 初始化,一些命令参数
- 用户登录之SHA1加密
- android 动态java代码设置背景以及字体等颜色
- 小软件公司怎么做大
- Python对于列表的del, remove, pop操作的区别
- Python3 大型网络爬虫实战 002 --- scrapy 爬虫项目的创建及爬虫的创建 --- 实例:爬取百度标题和CSDN博客
- sql之left join、right join、inner join的区别
- elasticsearch(一) 环境和工具
- Current measurement 和Voltage measurement 的用法_matlab/simulink
- unity之shader学习笔记(五)--纹理
- 微信小程序-仿开眼首页
- 欢迎使用CSDN-markdown编辑器
- 大数相减