它创建集合中的{{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