删除列表中第一项的函数(Python)
发布时间:2020-12-20 12:09:40 所属栏目:Python 来源:网络整理
导读:我正在尝试编写一个删除 Python列表中第一项的函数.这就是我尝试过的.当我调用函数时为什么不删除remove_first_wrong?当我在main函数中执行它时,为什么列表切片方法会起作用? def remove_first_wrong(lst): lst = lst[1:]def remove_first_right(lst): lst
我正在尝试编写一个删除
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,5] remove_first_right(l_2) print(l_2) # Why does this work and remove_first_wrong doesn't? l_3 = [1,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] 使用[:]是制作列表浅表副本的两种方法之一,请参阅How to clone or copy a list? 您可能需要阅读或观看Ned Batchelder’s Names and Values presestation,以进一步了解Python名称和对象的工作原理. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |