python 数组的del ,remove,pop区别

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

 
 
  1. >>> a=[1,2,3
  2. >>> a.remove(2
  3. >>> a 
  4. [13
  5. >>> a=[1,2,3
  6. >>> del a[1
  7. >>> a 
  8. [13
  9. >>> a= [1,2,3
  10. >>> a.pop(1
  11. 2 
  12. >>> a 
  13. [13
  14. >>>  

那么Python对于列表的del, remove, pop操作,它们之间有何区别呢?

首先,remove 是删除首个符合条件的元素。并不是删除特定的索引。如下例: 本文来自Novell迷网站 http://novell.me

 
 
  1. >>> a = [0223
  2. >>> a.remove(2
  3. >>> a 
  4. [023

而对于 del 来说,它是根据索引(元素所在位置)来删除的,如下例:

 
 
  1. >>> a = [3221
  2. >>> del a[1
  3. [321

第1个元素为a[0] --是以0开始计数的。则a[1]是指第2个元素,即里面的值2.

最后我们再看看pop

 
 
  1. >>> a = [435
  2. >>> a.pop(1
  3. 3 
  4. >>> a 
  5. [45

pop返回的是你弹出的那个数值。

所以使用时要根据你的具体需求选用合适的方法。 内容来自http://novell.me

另外它们如果出错,出错模式也是不一样的。注意看下面区别:

 
 
  1. >>> a = [456
  2. >>> a.remove(7
  3. Traceback (most recent call last): 
  4.   File "<stdin>", line 1in <module> 
  5. ValueError: list.remove(x): x not in list 
  6. >>> del a[7
  7. Traceback (most recent call last): 
  8.   File "<stdin>", line 1in <module> 
  9. IndexError: list assignment index out of range 
  10. >>> a.pop(7
  11. Traceback (most recent call last): 
  12.   File "<stdin>", line 1in <module> 
  13. IndexError: pop index out of range 

猜你喜欢

转载自blog.csdn.net/anneqiqi/article/details/71057069