这三种从列表中删除元素的方法有什么区别吗?
>>> 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]
这三种从列表中删除元素的方法有什么区别吗?
>>> 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]
当前回答
这里有很多很好的解释,但我会尽量简化。
其中,remove和pop是后缀,delete是前缀。
remove():用于删除第一次出现的元素。 删除(n) =>第一次出现在列表中的n。
>>> a = [0, 2, 3, 2, 1, 4, 6, 5, 7]
>>> a.remove(2) # where i = 2
>>> a
[0, 3, 2, 1, 4, 6, 5, 7]
pop():用于删除元素…
如果没有指定索引: Pop() =>从列表结束
>>> a.pop()
>>> a
[0, 3, 2, 1, 4, 6, 5]
如果指定了索引: Pop (index) = index的>
>>> a.pop(2)
>>> a
[0, 3, 1, 4, 6, 5]
警告:前方有危险
del():这是一个前缀方法。
注意相同方法的两种不同语法:带[]和不带。它有能力:
删除索引 Del a[index] =>用于删除索引和它的关联值,就像pop一样。
>>> del a[1]
>>> a
[0, 1, 4, 6, 5]
删除范围[index_1:index_N]中的值: 删除a[0:3] =>多个范围内的值。
>>> del a[0:3]
>>> a
[6, 5]
最后但并非最不重要的,删除整个列表在一个镜头。 如上所述,Del (a) =>。
>>> del (a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
希望这能澄清困惑。
其他回答
这里有很多很好的解释,但我会尽量简化。
其中,remove和pop是后缀,delete是前缀。
remove():用于删除第一次出现的元素。 删除(n) =>第一次出现在列表中的n。
>>> a = [0, 2, 3, 2, 1, 4, 6, 5, 7]
>>> a.remove(2) # where i = 2
>>> a
[0, 3, 2, 1, 4, 6, 5, 7]
pop():用于删除元素…
如果没有指定索引: Pop() =>从列表结束
>>> a.pop()
>>> a
[0, 3, 2, 1, 4, 6, 5]
如果指定了索引: Pop (index) = index的>
>>> a.pop(2)
>>> a
[0, 3, 1, 4, 6, 5]
警告:前方有危险
del():这是一个前缀方法。
注意相同方法的两种不同语法:带[]和不带。它有能力:
删除索引 Del a[index] =>用于删除索引和它的关联值,就像pop一样。
>>> del a[1]
>>> a
[0, 1, 4, 6, 5]
删除范围[index_1:index_N]中的值: 删除a[0:3] =>多个范围内的值。
>>> del a[0:3]
>>> a
[6, 5]
最后但并非最不重要的,删除整个列表在一个镜头。 如上所述,Del (a) =>。
>>> del (a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
希望这能澄清困惑。
使用del按索引删除元素,使用pop()按索引删除元素(如果需要返回值),使用remove()按值删除元素。最后一个需要搜索列表,如果列表中没有这样的值,则引发ValueError。
当从一个包含n个元素的列表中删除索引i时,这些方法的计算复杂度为
del O(n - i)
pop O(n - i)
remove O(n)
而pop和delete都采用索引来删除上面注释中所述的元素。一个关键的区别是它们的时间复杂度。没有索引的pop()的时间复杂度是O(1),但删除最后一个元素的情况不同。
如果您的用例总是删除最后一个元素,那么使用pop()而不是delete()总是更好的。有关时间复杂性的更多解释,请参阅https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
Remove主要作用于值。 删除和弹出工作在索引上
Remove基本上删除了第一个匹配的值。 Delete从指定索引中删除项 Pop基本上接受一个索引并返回该索引的值。下次打印列表时,该值不会出现。
下面是一个详细的答案。
Del可用于任何类对象,而pop和remove可用于特定类。
为del
下面是一些例子
>>> a = 5
>>> b = "this is string"
>>> c = 1.432
>>> d = myClass()
>>> del c
>>> del a, b, d # we can use comma separated objects
我们可以在用户创建的类中重写__del__方法。
具体用途与列表
>>> a = [1, 4, 2, 4, 12, 3, 0]
>>> del a[4]
>>> a
[1, 4, 2, 4, 3, 0]
>>> del a[1: 3] # we can also use slicing for deleting range of indices
>>> a
[1, 4, 3, 0]
为流行
Pop将索引作为参数,并删除该索引处的元素
与del不同,当在list object上调用pop时,返回该下标处的值
>>> a = [1, 5, 3, 4, 7, 8]
>>> a.pop(3) # Will return the value at index 3
4
>>> a
[1, 5, 3, 7, 8]
为消除
Remove获取参数值并从列表中删除该值。
如果存在多个值,则删除第一个值
注意:如果该值不存在,将抛出ValueError
>>> a = [1, 5, 3, 4, 2, 7, 5]
>>> a.remove(5) # removes first occurence of 5
>>> a
[1, 3, 4, 2, 7, 5]
>>> a.remove(5)
>>> a
[1, 3, 4, 2, 7]
希望这个答案对你有帮助。