yllplay 发表于 2015-12-3 13:54:55

python 数组的del ,remove,pop区别

  以a= 为例,似乎使用del, remove, pop一个元素2 之后 a都是为 , 如下:
  

[*]>>> a=
[*]>>> a.remove(2)
[*]>>> a
[*]
[*]>>> a=
[*]>>> del a
[*]>>> a
[*]
[*]>>> a=
[*]>>> a.pop(1)
[*]2
[*]>>> a
[*]
[*]>>>
  那么Python对于列表的del, remove, pop操作,它们之间有何区别呢?
  
  首先,remove 是删除首个符合条件的元素。并不是删除特定的索引。如下例: 本文来自Novell迷网站 http://novell.me

[*]>>> a =
[*]>>> a.remove(2)
[*]>>> a
[*]
  而对于 del 来说,它是根据索引(元素所在位置)来删除的,如下例:
  

[*]>>> a =
[*]>>> del a
[*]
  第1个元素为a --是以0开始计数的。则a是指第2个元素,即里面的值2.
  最后我们再看看pop

[*]>>> a =
[*]>>> a.pop(1)
[*]3
[*]>>> a
[*]
  pop返回的是你弹出的那个数值。
  所以使用时要根据你的具体需求选用合适的方法。 内容来自http://novell.me
  另外它们如果出错,出错模式也是不一样的。注意看下面区别:
  

[*]>>> a =
[*]>>> a.remove(7)
[*]Traceback (most recent call last):
[*]File "<stdin>", line 1, in <module>
[*]ValueError: list.remove(x): x not in list
[*]>>> del a
[*]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
页: [1]
查看完整版本: python 数组的del ,remove,pop区别