2014-11-24 227 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不能改變(有沒有辦法添加或刪除項目)。

相關問題