为什么 Python 集合不可散列?
问题描述
我偶然发现了一篇博客文章,详细介绍了如何在 Python 中实现 powerset 函数.所以我开始尝试自己的方法,发现 Python 显然不能有一组集合,因为集合是不可散列的.这很烦人,因为幂集的定义是它是一组集合,而我想使用实际的集合操作来实现它.
I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted to implement it using actual set operations.
>>> set([ set() ])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Python 集合不可散列是否有充分的理由?
Is there a good reason Python sets are not hashable?
解决方案
一般情况下,Python 中只有不可变对象是可散列的.set()
的不可变变体——frozenset()
——是可散列的.
Generally, only immutable objects are hashable in Python. The immutable variant of set()
-- frozenset()
-- is hashable.
相关文章