set是我们使用python的过程中经常用到的数据类型,以前只知道其具有去重的作用,但是对于其更加详细的信息却不得而知,相关的权威资料也不是很好找,想到了python(我这里差的是python3.6.3版本)官网的doc,应该会比较详细,详细地址请参考:官网对set的解释
查询结果果然没让人失望。首先看set的简介部分:
4.9. Set Types —
set
,frozenset
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in
dict
,list
, andtuple
classes, and thecollections
module.)Like other collections, sets support
x in set
,len(set)
, andfor x in set
. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.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.Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example:
{'jack', 'sjoerd'}
, in addition to theset
constructor.
4.9. set,frozenset
一个set对象是一个由无序可分对象组成的集合。常见的使用常见包括成员元素判断,去除序列中的重复元素,以及一些数学计算操作,例如交集,并集,差集。(对于其他容器类型,请参考内置的dict,list,tuple类,以及collections模块)
如同其他集合一般,集合操作支持 x in set, len(set) 以及for x in set等操作。作为一个无序集合,set不会记录成员对象的位置或者插入顺序。相应地,set也不支持所有,分片,或者其他当作序列操作的方式。
目前有另种内置set类型,为set和frozenset。set类型是可变的-内容可以使用诸如add() remove() 类的方法进行改变。因为其可变性质,因此其没有hash值(注意,这里所说的set没有哈希值是指set作为一个对象其本身没有哈希值,因为它是可以变化的,所有不可能存在哈希值,但是set的成员必须是可哈希的对象),从而无法用作字典的键值或者作为其他set的成员。frozenset类型是不可变、可哈希的-其内容一经创建之后就无法修改;因此其可用作字典键值或者作为另一个set集合的成员。
除了set的构造函数方式,非空set(不包括frozenset)也可以通过在花括号中使用逗号分割元素进行创建,例如 {'jack', 'sjoerd'}。