Why aren#39;t Python sets hashable?(为什么 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.
这篇关于为什么 Python 集合不可散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Python 集合不可散列?
基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
