del运算符如何在python中的列表中工作? [英] How does del operator work in list in python?
问题描述
我已经阅读了list
的python docs
以及del
运算符的工作原理,但是我需要对以下行为进行解释
I have read the python docs
for list
and how the del
operators works, but I need explanation for the following behavior
在这种情况下,c
和l
指向同一个对象(列表),因此对一个对象进行更改会影响另一个对象,但是删除一个对象不会删除该对象.那么这里发生了什么呢?只是列表对象的pointer
丢失了吗?
In this case, c
and l
points to the same object(list), so doing changes on one affects the other, but deleting one does not delete the object. So what happens here? Is it just the pointer
to the list object is lost?
>>> l = [1,2,3]
>>> c = l
>>> c.append(4)
>>> c
[1, 2, 3, 4]
>>> l
[1, 2, 3, 4]
>>> del c
>>> l
[1, 2, 3, 4]
>>> c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
通过分片操作删除
>>> l
[1, 2, 3, 4]
>>> del l[::2]
>>> l
[2, 4]
l[::2]
返回新列表.但是del l[::2]
可以就地删除.因此,在这种情况下,是否不会返回新列表?到底发生了什么事?
l[::2]
returns the new list. but del l[::2]
does in-place deletion. So in this case, is not a new list being returned? What exactly is happening here?
推荐答案
l
和c
被绑定到同一对象.它们都是对列表的引用,并且通过两个引用都可以操作该列表对象. del c
解除绑定 c
;它将删除对列表的引用.
l
and c
are bound to the same object. They both are references to a list, and manipulating that list object is visible through both references. del c
unbinds c
; it removes the reference to the list.
del l[::2]
从列表中删除一组特定的索引 ,您现在正在对列表对象自身进行操作.您未解除绑定l
,而是解除了列表的内部中的索引.
del l[::2]
removes a specific set of indices from the list, you are now operating on the list object itself. You are not unbinding l
, you are unbinding indices inside of the list.
您也可以将其与检索和设置值进行比较. print c
与print c[::2]
不同,并且c = something
与c[::2] = something
不同;这两个示例中的第一个示例仅访问列表对象,或为c
分配新值,后一个示例检索值的切片或为切片的索引设置新值.
You can compare this with retrieving and setting values as well. print c
is different from print c[::2]
and c = something
is different from c[::2] = something
; the first of both examples accesses just the list object, or assign a new value to c
, the latter examples retrieve a slice of values or set new values to the sliced indices.
在内部,del c
从处理所有变量的字典中删除名称c
(globals()
为您提供对此字典的引用). del l[::2]
调用列表中的 __delitem__
特殊方法,并传入slice()
对象.
Under the hood, del c
removes the name c
from the dictionary handling all variables (globals()
gives you a reference to this dictionary). del l[::2]
calls the __delitem__
special method on the list, passing in a slice()
object.
这篇关于del运算符如何在python中的列表中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!