列表上的 del、remove 和 pop 之间的区别 [英] Difference between del, remove, and pop on lists
本文介绍了列表上的 del、remove 和 pop 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从列表中删除元素的上述三种方法有什么区别吗?
解决方案
从列表中删除元素的三种不同方法的效果:
remove
删除第一个匹配的值,而不是特定的索引:
del
删除特定索引处的项目:
和 pop
删除特定索引处的项目并返回它.
它们的错误模式也不同:
<预><代码>>>>a = [4, 5, 6]>>>a.移除(7)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.ValueError: list.remove(x): x 不在列表中>>>德尔阿[7]回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.IndexError:列表分配索引超出范围>>>a.pop(7)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.索引错误:弹出索引超出范围>>> 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]
>>>
Is there any difference between the above three methods to remove an element from a list?
解决方案
The effects of the three different methods to remove an element from a list:
remove
removes the first matching value, not a specific index:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
del
removes the item at a specific index:
>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]
and pop
removes the item at a specific index and returns it.
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
Their error modes are different too:
>>> 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
这篇关于列表上的 del、remove 和 pop 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文