阅读文档:
del: Deletion of a target list recursively deletes each target, from left to right.
你能解释一下为什么这段代码能正常工作吗?
a = [1,2,3]
c = a[:]
del c
print a
del a[:]
print a
这打印:
[1, 2, 3]
[]
如果一个切片是一个指向原始列表相同元素的新列表,那么为什么删除一个切片的变量赋值不会使 a
为空以及为什么删除未引用的切片会删除元素一个
?
UPD
# -*- coding: utf-8 -*-
a = [1,2,3]
c = a[:]
def list_info(lst):
print "list id: {}".format(id(lst))
print "list of item ids:"
for item in lst:
print "id: {}; value: {}".format(id(item), item)
print ""
list_info(a)
list_info(c)
list_info(a[:])
打印:
list id: 26945296
list of item ids:
id: 23753600; value: 1
id: 23753588; value: 2
id: 23753576; value: 3
list id: 26920560
list of item ids:
id: 23753600; value: 1
id: 23753588; value: 2
id: 23753576; value: 3
list id: 26946136
list of item ids:
id: 23753600; value: 1
id: 23753588; value: 2
id: 23753576; value: 3
如您所见,所有列表项实际上都是相同的对象。
最佳答案
这是你正在做的:
a = [1,2,3]
创建新的列表对象。创建名称 a
指向它。
c = a[:]
创建列表对象的副本。创建名称 c
指向它。
del c
删除名称 c
。它过去指向的对象现在是垃圾,最终将被收集。这对第一个对象没有影响。
print a
打印a
指向的第一个对象。
del a[:]
删除a
指向的对象的所有元素。它现在是一个空列表。
print a
打印空列表。
那么,这些行之间有什么区别?
del c
del a[:]
第一行从命名空间中删除一个名称。第二行 从对象中删除元素。
编辑:我明白了,你不清楚他们为什么那样做。来自 Python Language Reference, Section 6.5 :
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a `global` statement in the same code block. If the name is unbound, a `NameError` exception will be raised.
这就是当您运行 del c
时发生的情况。
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
这就是当您运行 del a[:]
时发生的情况。
关于python - 阐明 python del 如何处理列表和切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874067/