# Python 数据类型 - 集合

Jinku Hu 2023年1月30日 2018年2月6日

Info

## 创建集合

``````>>> 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'>
``````

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

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

## 更新集合

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

>>> 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}
``````

## 删除集合中的元素

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

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

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

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

``````>>> 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()
``````

## 集合的操作

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

### 并集

``````>>> 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}
``````

### 交集

``````>>> 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}
``````

### 差集

``````>>> 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}
``````

### 对称差集

``````>>> 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()` 将集合更新为此集合和参数集合的并集

## 集合其他操作

### 集合成员检查

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

### 遍历集合

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

B
l
u
e
``````

## 适用于集合的内置函数

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

## Python 不可变集合

• `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})
``````
Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.