"del"、"remove"和"pop"在列表中的区别

38 浏览
0 Comments

"del"、"remove"和"pop"在列表中的区别

这三种方法从列表中删除元素有什么区别吗?

>>> a = [1, 2, 3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a = [1, 2, 3]
>>> del a[1]
>>> a
[1, 3]
>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]

admin 更改状态以发布 2023年5月25日
0
0 Comments

\n\n使用del通过索引删除元素,使用pop()如果需要返回值则通过索引删除元素,使用remove()通过值删除元素。最后一个方法需要在列表中进行搜索,并且如果列表中没有这样的值,则会引发 ValueError 。\n从包含n个元素的列表中删除索引i时,这些方法的计算复杂度为\n

del     O(n - i)
pop     O(n - i)
remove  O(n)

0
0 Comments

从列表中删除元素的三种不同方法的效果:

remove 方法删除第一个匹配的值,而不是特定的索引:

>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

del 方法删除指定索引处的元素:

>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]

pop 方法删除指定索引处的元素并返回它。

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

它们的错误模式也不同:

>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "", line 1, in 
IndexError: pop index out of range

0