Python对于列表的del, remove, pop操作的区别
来源:互联网 发布:员工工作证制作软件 编辑:程序博客网 时间:2024/06/05 03:16
首先,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对于文件的操作
- C++算法学习——数据结构——链表(2)
- 1003. 我要通过!(20)
- python爬虫之re正则表达式库
- CAEmitterLayer 详解
- 链表基础(C语言实现)
- Python对于列表的del, remove, pop操作的区别
- Xcode8 新建PrefixHeader.pch文件
- 华为软件精英挑战赛总结
- Ryu组件
- forward 和redirect权区别
- linu spi子系统驱动开发笔记之实例(2)
- odoo android 定制开发
- 通达OA 工作流流转过程中使用系统自带的提醒功能设置(图文)
- 2426: [HAOI2010]工厂选址 贪心