为什么Python集不能散列化?

2024-09-27 22:32:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我偶然发现一篇博客文章,详细介绍了如何在Python中实现powerset函数。所以我尝试了自己的方法,发现Python显然不能有一组集合,因为集合是不可散列的。这很烦人,因为powerset的定义是它是一组集合,我想使用实际的集合操作来实现它。

>>> set([ set() ])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

Python集不可散列有什么好的原因吗?


Tags: 方法函数inmost定义stdinline文章
3条回答

从Python文档:

hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() or cmp() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

通常,在Python中只有不可变的对象才是散列的。set()--frozenset()的不可变变量是散列的。

因为它们是可变的。

如果它们是散列的,散列可能会悄无声息地变得“无效”,这几乎会使散列变得毫无意义。

相关问题 更多 >

    热门问题