2014-11-24 93 views

回答

1

在Python中,一般而言,set等可变类型不是hashable。这不仅仅是因为它们不能被用作set元素或dict巧合键,这实际上整点:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id() .

frozenset类型存在相当多为此:

There are currently two built-in set types, set and frozenset . 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.

2

集合只能包含可哈希对象。但是它们本身不可散列。所以一个集合不能包含另一个集合。

(除此之外,你的代码有一个语法错误,因为{2}.3是无效的语法。但如果你将其更改为{{2}, 3, 4}它仍然是行不通的,因为我上面提到的原因。)

1

即使他们项目必须都是不可变/可哈希类型,集合本身是可变/不可哈希类型。您可以使用诸如set.addset.popset.remove等方法添加或删除组中的项目。因此,您无法将套件放入另一套套件中,因为该套件可能会随时更改。

相反,你可以使用一个frozenset,这是一个不可改变的/可哈希集:

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

但是请记住,这只是工作,因为在创建之后frozensets不能改变(有没有办法添加或删除项目)。

相关问题