删除,删除和弹出列表之间的区别

问题:删除,删除和弹出列表之间的区别

>>> 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]
>>> 

Is there any difference between the above three methods to remove an element from a list?


回答 0

是的,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 "<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

Yes, 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

回答 1

用于del按索引删除元素,pop()如果需要返回值,则按索引remove()删除元素,以及按值删除元素。后者需要搜索列表,并在列表中ValueError没有出现此类值时引发。

in元素列表中删除索引时,这些方法的计算复杂度为

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

Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value. The latter requires searching the list, and raises ValueError if no such value occurs in the list.

When deleting index i from a list of n elements, the computational complexities of these methods are

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

回答 2

由于没有其他人提到过它,因此请注意del(与一样pop)由于列表切片而允许删除一系列索引:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

IndexError如果索引不在列表中,这还可以避免使用an :

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

回答 3

已经被其他人很好地回答了。这是我的结尾:)

显然,pop是唯一返回值remove的对象,并且是唯一搜索对象的对象,同时del将自身限制为简单的删除。

Already answered quite well by others. This one from my end :)

Evidently, pop is the only one which returns the value, and remove is the only one which searches the object, while del limits itself to a simple deletion.


回答 4

这里有很多最佳的解释,但我会尽力简化一下。

在所有这些方法中,reverse和pop是后缀,而delete是prefix

remove():用于删除元素的第一次出现

remove(i) =>第一次出现i值

>>> 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) =>索引

>>>a.pop(2)
>>>a
[0, 3, 1, 4, 6, 5]

警告:危险方法提前

delete():它是一个前缀方法。

注意同一方法的两种不同语法:[]和()。它具有以下功能:

1.删​​除索引

del a[index] =>用于删除索引及其关联值,就像pop。

>>>del a[1]
>>>a
[0, 1, 4, 6, 5]

2.删除[index 1:index N]范围内的值

del a[0:3] =>范围内的多个值

>>>del a[0:3]
>>>a
[6, 5]

3.最后但不是列表,一次删除整个列表

del (a) =>如上所述。

>>>del (a)
>>>a

希望这可以澄清混淆。

Many best explanations are here but I will try my best to simplify more.

Among all these methods, reverse & pop are postfix while delete is prefix.

remove(): It used to remove first occurrence of element

remove(i) => first occurrence of i value

>>> 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(): It used to remove element if:

unspecified

pop() => from end of list

>>>a.pop()
>>>a
[0, 3, 2, 1, 4, 6, 5]

specified

pop(index) => of index

>>>a.pop(2)
>>>a
[0, 3, 1, 4, 6, 5]

WARNING: Dangerous Method Ahead

delete(): Its a prefix method.

Keep an eye on two different syntax for same method: [] and (). It possesses power to:

1.Delete index

del a[index] => used to delete index and its associated value just like pop.

>>>del a[1]
>>>a
[0, 1, 4, 6, 5]

2.Delete values in range [index 1:index N]

del a[0:3] => multiple values in range

>>>del a[0:3]
>>>a
[6, 5]

3.Last but not list, to delete whole list in one shot

del (a) => as said above.

>>>del (a)
>>>a

Hope this clarifies the confusion if any.


回答 5

pop-获取索引并返回值

remove-取值,删除第一个匹配项,不返回任何内容

delete-获取索引,删除该索引处的值,并且不返回任何内容

pop – Takes Index and returns Value

remove – Takes value, removes first occurrence, and returns nothing

delete – Takes index, removes value at that index, and returns nothing


回答 6

针对特定动作定义了对不同数据结构的任何操作/功能。在您的情况下,即删除一个元素,然后删除,弹出和删除。(如果考虑设置,则添加另一个操作-丢弃)添加时其他令人困惑的情况。插入/追加。为了演示,让我们实现双端队列。deque是一种混合线性数据结构,您可以在其中添加元素/从两端删除元素。(后端和前端)

class Deque(object):

  def __init__(self):

    self.items=[]

  def addFront(self,item):

    return self.items.insert(0,item)
  def addRear(self,item):

    return self.items.append(item)
  def deleteFront(self):

    return self.items.pop(0)
  def deleteRear(self):
    return self.items.pop()
  def returnAll(self):

    return self.items[:]

在这里,查看操作:

def deleteFront(self):

    return self.items.pop(0)
def deleteRear(self):
    return self.items.pop()

操作必须返回一些东西。因此,弹出-有和没有索引。如果我不想返回该值:del self.items [0]

按值删除而不是索引:

  • 去掉 :

    list_ez=[1,2,3,4,5,6,7,8]
    for i in list_ez:
        if i%2==0:
            list_ez.remove(i)
    print list_ez

返回[1,3,5,7]

让我们考虑一下集合的情况。

set_ez=set_ez=set(range(10))

set_ez.remove(11)

# Gives Key Value Error. 
##KeyError: 11

set_ez.discard(11)

# Does Not return any errors.

Any operation/function on different data structures is defined for particular actions. Here in your case i.e. removing an element, delete, Pop and remove. (If you consider sets, Add another operation – discard) Other confusing case is while adding. Insert/Append. For Demonstration, Let us Implement deque. deque is a hybrid linear data structure, where you can add elements / remove elements from both ends.(Rear and front Ends)

class Deque(object):

  def __init__(self):

    self.items=[]

  def addFront(self,item):

    return self.items.insert(0,item)
  def addRear(self,item):

    return self.items.append(item)
  def deleteFront(self):

    return self.items.pop(0)
  def deleteRear(self):
    return self.items.pop()
  def returnAll(self):

    return self.items[:]

In here, see the operations:

def deleteFront(self):

    return self.items.pop(0)
def deleteRear(self):
    return self.items.pop()

Operations have to return something. So, pop – With and without an index. If I don’t want to return the value: del self.items[0]

Delete by value not Index:

  • remove :

    list_ez=[1,2,3,4,5,6,7,8]
    for i in list_ez:
        if i%2==0:
            list_ez.remove(i)
    print list_ez
    

Returns [1,3,5,7]

let us consider the case of sets.

set_ez=set_ez=set(range(10))

set_ez.remove(11)

# Gives Key Value Error. 
##KeyError: 11

set_ez.discard(11)

# Does Not return any errors.

回答 7

pop和delete都带有索引,以删除元素,如上面的注释所述。一个关键的区别是它们的时间复杂度。没有索引的pop()的时间复杂度为O(1),但删除最后一个元素的情况不同。

如果您的用例始终是删除最后一个元素,则始终首选使用pop()而不是delete()。有关时间复杂度的更多说明,请参阅https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt

While pop and delete both take indices to remove an element as stated in above comments. A key difference is the time complexity for them. The time complexity for pop() with no index is O(1) but is not the same case for deletion of last element.

If your use case is always to delete the last element, it’s always preferable to use pop() over delete(). For more explanation on time complexities, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt


回答 8

列表上的删除操作具有要删除的值。它搜索列表以查找具有该值的项目,然后删除找到的第一个匹配项目。如果没有匹配的项目,将引发ValueError,这是一个错误。

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

德尔语句可以用来删除整个列表。如果您有一个特定的列表项作为del的参数(例如,listname [7]专门引用列表中的第8个项),则将其删除。甚至有可能从列表中删除“片段”。如果索引超出范围,则会引发IndexError,这是一个错误。

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

pop的通常用法是在将列表用作堆栈时从列表中删除最后一项。与del不同,pop返回从列表中弹出的值。您可以选择提供一个索引值来从列表的末尾弹出和弹出(例如listname.pop(0)将从列表中删除第一项并返回该第一项作为结果)。您可以使用它使列表表现得像队列一样,但是有一些库例程可以提供比pop(0)更好的队列操作性能。如果索引超出范围,则会引发IndexError,这是一个错误。

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

有关更多详细信息,请参见collections.deque

The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it’ll just delete that item. It is even possible to delete a “slice” from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.


回答 9

删除基本上对值起作用。删除并弹出索引上的工作

删除基本上删除第一个匹配值。Delete从特定索引中删除项目。Pop基本上会获取一个索引并返回该索引处的值。下次打印列表时,该值不会出现。

Remove basically works on the value . Delete and pop work on the index

Remove basically removes the first matching value. Delete deletes the item from a specific index Pop basically takes an index and returns the value at that index. Next time you print the list the value doesnt appear.


回答 10

您也可以使用remove来删除索引值。

n = [1, 3, 5]

n.remove(n[1])

n然后将指代[1,5]

You can also use remove to remove a value by index as well.

n = [1, 3, 5]

n.remove(n[1])

n would then refer to [1, 5]