它創建集合中的{{2}.3,4}
set元素時給我錯誤。爲什麼不能將一個集合作爲一個集合的元素?
錯誤:
File "<stdin>", line 1
{{2}.3,4}
^
有沒有替代的方式來做到這一點? 在此先感謝。
它創建集合中的{{2}.3,4}
set元素時給我錯誤。爲什麼不能將一個集合作爲一個集合的元素?
錯誤:
File "<stdin>", line 1
{{2}.3,4}
^
有沒有替代的方式來做到這一點? 在此先感謝。
在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
andfrozenset
. Theset
type is mutable — the contents can be changed using methods likeadd()
andremove()
. 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. Thefrozenset
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}.3
是無效的語法。但如果你將其更改爲{{2}, 3, 4}
它仍然是行不通的,因爲我上面提到的原因。)
即使他們項目必須都是不可變/可哈希類型,集合本身是可變/不可哈希類型。您可以使用諸如set.add
,set.pop
或set.remove
等方法添加或刪除組中的項目。因此,您無法將套件放入另一套套件中,因爲該套件可能會隨時更改。
相反,你可以使用一個frozenset
,這是一個不可改變的/可哈希集:
>>> {frozenset({2}), 3,4}
set([frozenset([2]), 3, 4])
>>>
但是請記住,這只是工作,因爲在創建之後frozensets不能改變(有沒有辦法添加或刪除項目)。
HTTP: //stackoverflow.com/questions/5931291/how-can-i-create-a-set-of-sets-in-python – Maroun 2014-11-24 20:35:42