Python 数据类型 - 集合

Jinku Hu 2023年1月30日
  1. 创建集合
  2. 更新集合
  3. 删除集合中的元素
  4. 集合的操作
  5. 集合方法
  6. 集合其他操作
  7. 适用于集合的内置函数
  8. Python 不可变集合
Python 数据类型 - 集合

我们将来学习在 Python 中如何创建集合,以及如何增加和删除其中的元素。

Info

集合包含了不重复以及没有排序的元素。

集合是可变数据类型,所以你可以增加或者删除集合中的元素。

创建集合

集合可以通过大括号 {} 来创建,里面的元素用逗号 , 来分开。你也可以通过 Python 的内置函数 set() 来创建集合。

集合中的元素可以为不同的数据类型,而且元素必须是不可变数据类型,比如,元组可以作为集合的元素,但是集合、列表或者字典就不能是集合的元素。

>>> x = {3, 5, 7, 2, 4, 5}		
>>> print(x)		#prints the set variable
{2, 3, 4, 5, 7}
>>> print(type(x))		#checking type of x
<class 'set'>

你可以通过 set() 函数 with empty parameters to create an empty list. If you write {} to create an empty object, it is interpreted as a dictionary:

>>> x = {}
>>> print(type(x))
<class 'dict'>

>>> x = set()
>>> print(type(x))
<class 'set'>

更新集合

索引和切片操作不能用来更新集合中的元素,因为集合不是一个有序的数据类型。可以通过 add() 方法来向集合中添加一个新元素,如果你想添加多个元素的话,可以使用 update() 方法。

>>> s = {2, 4}
>>> print(s)
{2, 4}

>>> s.add(6)
>>> print(s)
{2, 4, 6}

>>> s.update([2, 4, 6])
>>> print(s)
{2, 4, 6}

>>> s.update([5,6], {7, 8, 9})
>>> print(s)
{2, 4, 5, 6, 7, 8, 9}

删除集合中的元素

集合可以通过 discard()remove() 方法来删除其中的某个元素。discard()remove() 方法的差别在于当要去除的元素在集合中不存在时,discard() 不会报错,而 remove() 会产生错误信息。

>>> s = {2, 4, 5, 6, 7, 8, 9}
>>> print(s)
{2, 4, 5, 6, 7, 8, 9}

>>> s.discard(6)
>>> print(s)
{2, 4, 5, 7, 8, 9}

>>> s.remove(8)
>>> print(s)
{2, 4, 5, 7, 9}

>>> s.discard(6)		#no error
>>> s.remove(8)			#generated an error
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    s.remove(8)
KeyError: 8

你可以通过 pop() 方法来删除集合中的一个元素,但 pop() 方法删除的元素可能是集合中的任意的一个元素。

>>> s = set("Python")
>>> s
{'o', 'n', 'h', 'P', 'y', 't'}
>>> s.pop()
o
>>> s.pop()
n
>>> s
{'h', 'P', 'y', 't'}
>>> s.clear()
>>> print(s)
set()

clear() 方法是用来删除集合中的所有元素。

>>> s = set("Python")
>>> s.clear()
>>> s
set()

集合的操作

集合的操作方法包括以下几种,比如 unionintersectiondifferencesymmetric_difference

假设你有下面两个集合 xy:

>>> x = {1, 2, 3, 4, 5, 6}
>>> y = {7, 8, 9, 10, 11, 12}

并集

两个集合的并集是包含两集合中所有元素的集合,Python 中可以使用 | 操作符或者 union() 方法来求两集合的并集。

>>> print(x | y)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

#using union() method on x
>>> x.union(y)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
#union on y
>>> y.union(x)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

交集

两个集合的并集是在两集合中都有的元素的集合,Python 中可以使用 & 操作符或者 intersection() 方法来求两集合的交集。

>>> x = {1, 2, 3, 4, 5, 6}
>>> y = {7, 8, 9, 2, 6, 1}
>>> print(x & y)
{1, 2, 6}

#using intersection() method on x
>>> x.intersection(y)
{1, 2, 6}
#intersection on y
>>> y.intersection(x)
{1, 2, 6}

差集

集合 xy 的差集是元素在 x 中存在,而在 y 中不存在的元素的集合,比如,x - y 中的元素在集合 x 而不在集合 y 中。Python 可以使用操作符 - 或者 difference() 方法来求差集。

>>> x = {1, 2, 3, 4, 5, 6}
>>> y = {7, 8, 9, 2, 6, 1}
>>> print(x - y)
{3, 4, 5}

#using difference() method on x
>>> x.difference(y)
{3, 4, 5}
#diference on y
>>> y.difference(x)
{8, 9, 7}

对称差集

对称差集是其中的元素不同时在两个集合中出现的集合,Python 求对称差集可以使用^操作符或者 symmetric_difference() 方法。

>>> x = {1, 2, 3, 4, 5, 6}
>>> y = {7, 8, 9, 2, 6, 1}
>>> print(x ^ y)
{3, 4, 5, 7, 8, 9}

#using symmetric_difference() method on x
>>> x.symmetric_difference(y)
{3, 4, 5, 7, 8, 9}
#symmetric_diference on y
>>> y.symmetric_difference(x)
{3, 4, 5, 7, 8, 9}

集合方法

方法 描述
add() 增加一个元素到集合
clear() 清空整个集合
copy() 返回集合的拷贝(浅拷贝)
difference() 求差集
difference_update() 求差集并且将集合更新为该差集
discard() 从集合中删除某一元素
intersection() 求交集
intersection_update() 求交集并且将集合更新为该交集
isdisjoint() 当两个集合没有交集时,返回 True
issubset() 当另外一个集合包含此集合时,返回 True
issuperset() 当该集合包含另外一个集合时,返回 True
pop() 从集合弹出一任意元素
remove() 从集合中删除某一元素,假如集合中不存在该元素,报错
symmetric_difference() 求对称交集
symmetric_difference_update() 求对称交集,并将该集合更新为此对称交集
union() 求并集
update() 将集合更新为此集合和参数集合的并集

集合其他操作

集合成员检查

可以使用 in 关键字来检查某元素是否存在在集合中。

>>> s = set("Blue")
>>> print('o' in s)
False
>>> print('l' in s)
True

遍历集合

你可以通过 for 循环来遍历集合。

>>> for i in set("Blue"):
    print(i)

B
l
u
e 

适用于集合的内置函数

以下是 Python 中适用于集合的内置函数的列表

函数 描述
all() 如果集合中有所有元素为 True 返回 True,当集合为空时,返回 True
any() 如果集合中有一个元素为 True 返回 True,当集合为空时,返回 False
enumerate() 返回所有元素的索引和元素本身,索引和元素组成一个元组;最终返回的是一个 enumerate 类型
len() 返回集合中的元素数目或者集合的长度
set() 定义一个集合
max() 返回集合中元素的最大值
min() 返回集合中元素的最小值
sorted() 返回一个包含集合所有元素的排序列表
sum() 返回集合中所有元素的总和

Python 不可变集合

不可变集合是一种特殊集合,它在被赋值后元素不能被更新和修改。不可变集合是不可变类型的集合。

集合是可变类型的,所以你无法把它作为词典的键,但因为不可变集合是不可变类型的,所以它是可以作为字典的键的。

不可变集合可以用 frozenset() 来创建,fronzenset 支持以下的方法:

  • copy()
  • difference()
  • intersection()
  • isdisjoint()
  • issubset()
  • issuperset()
  • symmetric_difference()
  • union()
>>> x = frozenset([2,6,3,9])
>>> y = frozenset([6,1,2,4])
>>> x.difference(y)
frozenset({9, 3})
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

DelftStack.com 创始人。Jinku 在机器人和汽车行业工作了8多年。他在自动测试、远程测试及从耐久性测试中创建报告时磨练了自己的编程技能。他拥有电气/电子工程背景,但他也扩展了自己的兴趣到嵌入式电子、嵌入式编程以及前端和后端编程。

LinkedIn Facebook