簡體   English   中英

刪除列表中第一項的函數(Python)

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

我正在嘗試編寫一個刪除Python列表中第一項的函數。 這就是我嘗試過的。 當我調用函數時為什么不刪除remove_first_wrong? 當我在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)

切片列表會返回一個新的列表對象,它是您在切片中指示的原始列表索引的副本。 然后,您將反彈lst (函數中的本地名稱)以引用該新列表。 在此過程中永遠不會更改舊列表。

另一方面, list.pop()對列表對象本身進行操作。 您使用什么參考到達列表並不重要。

沒有函數你會看到同樣的事情:

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

使用[:]是制作列表淺表副本的兩種方法之一,請參閱如何克隆或復制列表?

您可能想要閱讀或觀看Ned Batchelder的名稱和值預測 ,以進一步了解Python名稱和對象的工作原理。

在函數remove_first_wrong= sign將名稱lst重新分配給右側的對象。 這是一個全新的對象,通過切片操作lst[1:] 因此,分配給的對象lst對於該函數是本地的(並且它實際上將在返回時消失)。

這就是Martijn所說的“你然后反彈lst (函數中的本地名稱)來引用這個新列表。”

相反, lst.pop(0)是對給定對象的調用 - 它對對象進行操作。

例如,這也可以正常工作:

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

或者,您可以使用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