加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

为什么在Python中没有实现嵌套?

发布时间:2020-12-20 12:38:04 所属栏目:Python 来源:网络整理
导读:li = [2,[3,4]] 3 in liFalse {2,{3,4}}TypeError: unhashable type: 'set' 为什么在Python(2.x和3.x)中没有实现嵌套(在数学中使用)? 解决方法 它已实现,但您需要使用 hashable type. frozenset() 就是那种.文档甚至告诉你: To represent sets of sets,the
>>> li = [2,[3,4]]
>>> 3 in li
False

>>> {2,{3,4}}
TypeError: unhashable type: 'set'

为什么在Python(2.x和3.x)中没有实现嵌套(在数学中使用)?

解决方法

它已实现,但您需要使用 hashable type. frozenset()就是那种.文档甚至告诉你:

To represent sets of sets,the inner sets must be frozenset objects.

演示:

>>> {2,frozenset([3,4])}
set([frozenset([3,4]),2])

这是因为常规set()是可变的,这与用于集合(和字典)的数据结构的要求不兼容;这些需要稳定的对象,当根据其哈希值用作表中的键时可以重新定位.

文档再次:

The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable,it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读