为什么 Python 集不可散列? [英] Why aren't Python sets hashable?

查看:25
本文介绍了为什么 Python 集不可散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>设置([设置()])回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:不可散列的类型:设置"

Python 集不可散列是否有充分的理由?

解决方案

一般来说,Python 中只有不可变对象是可散列的.set() 的不可变变体 -- frozenset() -- 是可散列的.

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'

Is there a good reason Python sets are not hashable?

解决方案

Generally, only immutable objects are hashable in Python. The immutable variant of set() -- frozenset() -- is hashable.

这篇关于为什么 Python 集不可散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆