Python set 集合特点与运算
· 阅读需 6 分钟

Set(集合)是一个无序的不重复元素序列。
创建
可以使用大括号 { }
或者 set()
函数创建集合:
set1 = {value1, value2, ...}
# or
set2 = set(value)
警告
- set2 中的
value
必须是 iterable,比如 string, list,不能是 int。 - 创建一个空集合必须用
set()
而不是{ }
,因为{ }
是用来创建一个空字典。
>>> print({1, 2, 3})
{1, 2, 3}
>>> print(set([1, 2, 3]))
{1, 2, 3}
去重
集合具有天然去重的功能:
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'orange', 'banana', 'pear', 'apple'}
元素与集合关系
in
∈
判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False。类似数学中的 ∈
符号。
x in s
>>> 'apple' in basket
True
>>> 'peach' in basket
False
not in
∉
判断元素 x 是否不在集合 s 中,类似数学中的 ∉
符号。
x not in s
>>> 'apple' not in basket
False
>>> 'peach' not in basket
True
集合间运算
>>> set1 = set('abcde')
>>> set2 = set('defgh')
>>> set1
{'a', 'b', 'c', 'd', 'e'}
>>> set2
{'d', 'e', 'f', 'g', 'h'}
<
, <=
子集
>>> set1 < set2
False
>>> set('def') < set2
True
set1.issubset(set2)
判断 set1 是否为 set2 的子集。
>>> set1.issubset(set2)
False
>>> set('def').issubset(set2)
False
>
, >=
超集
>>> set1 > set2
False
>>> set('defghijk') > set2
True
set1.issuperset(set2)
判断 set1 是否为 set2 的超集。
>>> set1.issuperset(set2)
False
>>> set('defghijk').issuperset(set2)
True
&
交集
集合 set1 和 set2 中都包含了的元素,如下图所示:

>>> set1 & set2
{'d', 'e'}
set1.intersection(set2, set3 ... etc)
>>> set1.intersection(set2)
{'d', 'e'}
set1.intersection_update(set2, set3 ... etc)
intersection_update()
方法其实就是将 intersection()
方法返回的新集合,重 新赋值给 set1。该方法没有返回值。
>>> set1.intersection_update(set2)
>>> set1
{'d', 'e'}
set1.isdisjoint(set2)
判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
>>> set1.isdisjoint(set2)
False
|
并集
集合 set1 或 set2 中包含的所有元素,如下图所示:

>>> set1 | set2
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}
set1.union(set2, set3 ... etc)
>>> set1.union(set2)
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}
-
差集
集合 set1 中包含而集合 set2 中不包含的元素,如下图所示:

>>> set1 - set2
{'a', 'b', 'c'}
set1.difference(set2)
>>> set1.difference(set2)
{'a', 'b', 'c'}
set1.difference_update(set2)
difference_update()
方法其实就是将 difference()
方法返回的新集合,重新赋值给 set1 。该方法没有返回值。
>>> set1.difference_update(set2)
>>> set1
{'a', 'b', 'c'}
^
对称差集
不同时包含于 set1 和 set2 的元素,如下图所示:

>>> set1 ^ set2
{'a', 'b', 'c', 'f', 'g', 'h'}
set1.symmetric_difference(set2)
>>> set1.symmetric_difference(set2)
{'a', 'b', 'c', 'f', 'g', 'h'}
set1.symmetric_difference_update(set2)
symmetric_difference_update()
方法其实就是将 symmetric_difference()
方法返回的新集合,重新赋值给 set1。该方法没有返回值。
>>> set1.symmetric_difference_update(set2)
>>> set1
{'a', 'b', 'c', 'f', 'g', 'h'}