为什么我不能在字典上调用 del [:] ?
这是怎么回事?
>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}
为什么我必须调用 dict.clear
?
What's going on here?
>>> a = {1: "a", 2: "b"}
>>> del a[1]
>>> a
{2: 'b'}
>>> a = {1: "a", 2: "b"}
>>> del a[:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
>>> a.clear()
>>> a
{}
Why must I call dict.clear
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
a[:]
是切片操作的一种特殊情况,它仅为序列定义。它是a[0:len(a)]
的缩写形式。字典不是序列。a[:]
is a special case of a slicing operation, which is defined only for sequences. It is a short form ofa[0:len(a)]
. A dict is not a sequence.a[:]
是制作列表
(和元组
)浅表副本的快速方法。有关不同类型复制的说明,请参阅文档的底部。因此,有理由说字典上的 del a[:] 并没有多大意义。
如果你想删除整个字典,你可以简单地执行
del a
a[:]
is a quick way to make a shallow copy of alist
(andtuple
). See towards the bottom of the docs for clarification on different types of copying.Thus, it would reason to say that del a[:] on a dictionary doesn't really make much sense.
If you want to delete the entire dictionary, you can simply do
del a
原因很简单:它没有定义。如果有人花精力捕捉空切片并委托给适当的方法,那么它就没有理由不起作用。
另一方面,这会违反分配和获取相同切片的对称原则,因此可能不会获得接受。
The reason is rather simple: It isn't defined. There's no reason why it couldn't work, if someone put the effort into catching the empty slice and delegating to the appropriate method.
On the other hand, this would violate a symmetry principle with assigning and getting the same slice, so probably would not gain acceptance.
如果此功能对您的系统至关重要,您可以对内置 dict 进行子类化以添加此功能。
If this functionality is crucial to your system, you could subclass the dict builtin to add this function.
当您执行
del a[1]
时,您不会删除字典中的第一个元素,而是删除键为 1 的元素。字典没有任何排序,因此没有切片算法(在至少在这种情况下)。这就是为什么使用字典
a = {1 : 'one', 5 : ' Five'}
可以执行del a[1]
而不能执行del a [2]
或del a[0]
When you're doing
del a[1]
you're not deleting the first element in dictionary, you're deleting the element with key 1. Dictionary does not have any ordering and thus slicing algorigthm (in this case at least).That's why with the dict
a = {1 : 'one', 5 : 'five'}
you can dodel a[1]
and cannot dodel a[2]
ordel a[0]