set 对象是由具有唯一性的 hashable 对象所组成的无序多项集。 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算,例如交集、并集、差集与对称差集等等。
与其他多项集一样,集合也支持 x in set
, len(set)
和 for x in set
。 作为一种无序的多项集,集合并不记录元素位置或插入顺序。 相应地,集合不支持索引、切片或其他序列类的操作。
class set([iterable])
class frozenset([iterable])
返回一个新的 set 或 frozenset 对象,其元素来自于 iterable。 集合的元素必须为 hashable。 要表示由集合对象构成的集合,所有的内层集合必须为 frozenset
对象。 如果未指定 iterable,则将返回一个新的空集合。
集合可用多种方式来创建:
- 使用花括号内以逗号分隔元素的方式:
{'jack', 'sjoerd'}
- 使用集合推导式:
{c for c in 'abracadabra' if c not in 'abc'}
- 使用类型构造器:
set()
, set('foobar')
, set(['a', 'b', 'foo'])
返回集合 s 中的元素数量(即 s 的基数)。 检测 x 是否为 s 中的成员。 检测 x 是否非 s 中的成员。 如果集合中没有与 other 共有的元素则返回 检测是否集合中的每个元素都在 other 之中。 检测集合是否为 other 的真子集,即 检测是否 other 中的每个元素都在集合之中。 检测集合是否为 other 的真超集,即 返回一个新集合,其中包含来自原集合以及 others 指定的所有集合中的元素。 返回一个新集合,其中包含原集合以及 others 指定的所有集合中共有的元素。 返回一个新集合,其中包含原集合中在 others 指定的其他集合中不存在的元素。 返回一个新集合,其中的元素或属于原集合或属于 other 指定的其他集合,但不能同时属于两者。 返回原集合的浅拷贝。len(s)
x in s
x not in s
isdisjoint
(other)True
。 当且仅当两个集合的交集为空集合时,两者为不相交集合。issubset
(other)set <= other
set < other
set <= other and set != other
。issuperset
(other)set >= other
set > other
set >= other and set != other
。union
(*others)set | other | ...
intersection
(*others)set & other & ...
difference
(*others)set - other - ...
symmetric_difference
(other)set ^ other
copy
()