简体   繁体   English

删除列表中第一项的函数(Python)

[英]Function which removes the first item in a list (Python)

I am trying to write a function which removes the first item in a Python list. 我正在尝试编写一个删除Python列表中第一项的函数。 This is what I've tried. 这就是我尝试过的。 Why doesn't remove_first_wrong change l when I call the function on it? 当我调用函数时为什么不删除remove_first_wrong? And why does the list slicing approach work when I do it in the main function? 当我在main函数中执行它时,为什么列表切片方法会起作用?

def remove_first_wrong(lst):
    lst = lst[1:]

def remove_first_right(lst):
    lst.pop(0)

if __name__ == '__main__':
    l = [1, 2, 3, 4, 5]
    remove_first_wrong(l)
    print(l)

    l_2 = [1, 2, 3, 4, 5]
    remove_first_right(l_2)
    print(l_2)

    # Why does this work and remove_first_wrong doesn't?
    l_3 = [1, 2, 3, 4, 5]
    l_3 = l_3[1:]
    print(l_3)

Slicing a list returns a new list object, which is a copy of the original list indices you indicated in the slice. 切片列表会返回一个新的列表对象,它是您在切片中指示的原始列表索引的副本。 You then rebound lst (a local name in the function) to reference that new list instead. 然后,您将反弹lst (函数中的本地名称)以引用该新列表。 The old list is never altered in that process. 在此过程中永远不会更改旧列表。

list.pop() on the other hand, operates on the list object itself. 另一方面, list.pop()对列表对象本身进行操作。 It doesn't matter what reference you used to reach the list. 您使用什么参考到达列表并不重要。

You'd see the same thing without functions: 没有函数你会看到同样的事情:

>>> a = [1, 2]
>>> b = a[:]  # slice with all the elements, produces a *copy*
>>> b
[1, 2]
>>> a.pop()  # remove an element from a won't change b
2
>>> b
[1, 2]
>>> a
[1]

Using [:] is one of two ways of making a shallow copy of a list, see How to clone or copy a list? 使用[:]是制作列表浅表副本的两种方法之一,请参阅如何克隆或复制列表?

You may want to read or watch Ned Batchelder's Names and Values presestation , to further help understand how Python names and objects work. 您可能想要阅读或观看Ned Batchelder的名称和值预测 ,以进一步了解Python名称和对象的工作原理。

Inside the function remove_first_wrong the = sign reassigns the name lst to the object on the right. 在函数remove_first_wrong= sign将名称lst重新分配给右侧的对象。 Which is a brand new object, created by slicing operation lst[1:] . 这是一个全新的对象,通过切片操作lst[1:] Thus, the object lst assigned to is local to that function (and it actually will disappear on return). 因此,分配给的对象lst对于该函数是本地的(并且它实际上将在返回时消失)。

That is what Martijn means by "You then rebound lst (a local name in the function) to reference that new list instead." 这就是Martijn所说的“你然后反弹lst (函数中的本地名称)来引用这个新列表。”

On contrary, lst.pop(0) is a call to the given object -- it operates on the object. 相反, lst.pop(0)是对给定对象的调用 - 它对对象进行操作。

For example, this will work right too: 例如,这也可以正常工作:

def remove_first_right2(lst):
    x = lst  # x is assigned to the same object as lst
    x.pop(0) # pop the item from the object

Alternately, you can use del keyword: 或者,您可以使用del关键字:

def remove_first_element(lst):
   del lst[0]
   return lst

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM