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 集合不可散列?
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
