在本教程中,您将学习有关 Python 集的所有知识。 如何创建它们,从中添加元素或从中删除元素,以及在 Python 中对集合执行的所有操作。
集合是项目的无序集合。 每个集的元素都是唯一的(没有重复),并且必须是不可变的(无法更改)。
但是,集合本身是可变的。 我们可以从中添加或删除项目。
集还可以用于执行数学集运算,例如并集,交集,对称差等。
创建 Python 集
通过将所有项目(元素)放置在大括号{}中(用逗号分隔)或使用内置的set()函数,可以创建一个集合。
它可以具有任意数量的项目,并且它们可以具有不同的类型(整数,浮点数,元组,字符串等)。 但是集合不能具有可变元素,例如列表,集合或字典作为其元素。
# Different types of sets in Python# set of integersmy_set = {1, 2, 3}print(my_set)# set of mixed datatypesmy_set = {1.0, "Hello", (1, 2, 3)}print(my_set)
输出
{1, 2, 3}{1.0, (1, 2, 3), 'Hello'}
也尝试以下示例。
# set cannot have duplicates# Output: {1, 2, 3, 4}my_set = {1, 2, 3, 4, 3, 2}print(my_set)# we can make set from a list# Output: {1, 2, 3}my_set = set([1, 2, 3, 2])print(my_set)# set cannot have mutable items# here [3, 4] is a mutable list# this will cause an error.my_set = {1, 2, [3, 4]}
输出:
{1, 2, 3, 4}{1, 2, 3}Traceback (most recent call last):File "<string>", line 15, in <module>my_set = {1, 2, [3, 4]}TypeError: unhashable type: 'list'
创建一个空集有点棘手。
空花括号{}将在 Python 中创建一个空字典。 为了创建没有任何元素的集合,我们使用不带任何参数的set()函数。
# Distinguish set and dictionary while creating empty set# initialize a with {}a = {}# check data type of aprint(type(a))# initialize a with set()a = set()# check data type of aprint(type(a))
输出:
<class 'dict'><class 'set'>
在 Python 中修改集
集是可变的。 但是,由于它们是无序的,因此索引没有意义。
我们无法使用索引或切片来访问或更改集合的元素。 设置数据类型不支持它。
我们可以使用add()方法添加一个元素,并使用update()方法添加多个元素。update()方法可以将元组,列表,字符串或其他集合用作其参数。 在所有情况下,都避免重复。
# initialize my_setmy_set = {1, 3}print(my_set)# if you uncomment line 9,# you will get an error# TypeError: 'set' object does not support indexing# my_set[0]# add an element# Output: {1, 2, 3}my_set.add(2)print(my_set)# add multiple elements# Output: {1, 2, 3, 4}my_set.update([2, 3, 4])print(my_set)# add list and set# Output: {1, 2, 3, 4, 5, 6, 8}my_set.update([4, 5], {1, 6, 8})print(my_set)
输出:
{1, 3}{1, 2, 3}{1, 2, 3, 4}{1, 2, 3, 4, 5, 6, 8}
从集中删除元素
可以使用discard()和remove()方法从集合中移除特定项目。
两者之间的唯一区别是,如果元素中不存在discard()函数,则该集合将保持不变。 另一方面,在这种情况下,remove()函数将引发错误(如果集合中不存在元素)。
以下示例将说明这一点。
# Difference between discard() and remove()# initialize my_setmy_set = {1, 3, 4, 5, 6}print(my_set)# discard an element# Output: {1, 3, 5, 6}my_set.discard(4)print(my_set)# remove an element# Output: {1, 3, 5}my_set.remove(6)print(my_set)# discard an element# not present in my_set# Output: {1, 3, 5}my_set.discard(2)print(my_set)# remove an element# not present in my_set# you will get an error.# Output: KeyErrormy_set.remove(2)
输出:
{1, 3, 4, 5, 6}{1, 3, 5, 6}{1, 3, 5}{1, 3, 5}Traceback (most recent call last):File "<string>", line 28, in <module>KeyError: 2
同样,我们可以使用pop()方法删除并返回一个项目。
由于集是无序数据类型,因此无法确定将弹出哪个项目。 这是完全任意的。
我们还可以使用clear()方法从集合中删除所有项目。
# initialize my_set# Output: set of unique elementsmy_set = set("HelloWorld")print(my_set)# pop an element# Output: random elementprint(my_set.pop())# pop another elementmy_set.pop()print(my_set)# clear my_set# Output: set()my_set.clear()print(my_set)print(my_set)
输出:
{'H', 'l', 'r', 'W', 'o', 'd', 'e'}H{'r', 'W', 'o', 'd', 'e'}set()
Python 集操作
集合可用于执行数学集合运算,例如并集,交集,差和对称差。 我们可以使用运算符或方法来做到这一点。
让我们考虑以下两组用于以下操作。
>>> A = {1, 2, 3, 4, 5}>>> B = {4, 5, 6, 7, 8}
并集

Python 中的并集
A和B的并集是两个集合中所有元素的集合。
联合使用|运算符执行。 使用union()方法可以完成相同的操作。
# Set union method# initialize A and BA = {1, 2, 3, 4, 5}B = {4, 5, 6, 7, 8}# use | operator# Output: {1, 2, 3, 4, 5, 6, 7, 8}print(A | B)
输出:
{1, 2, 3, 4, 5, 6, 7, 8}
在 Python shell 上尝试以下示例。
# use union function>>> A.union(B){1, 2, 3, 4, 5, 6, 7, 8}# use union function on B>>> B.union(A){1, 2, 3, 4, 5, 6, 7, 8}
交集

Python 中的交集
A和B的交集是在这两组中都相同的一组元素。
交叉使用&运算符执行。 使用intersection()方法可以完成相同的操作。
# Intersection of sets# initialize A and BA = {1, 2, 3, 4, 5}B = {4, 5, 6, 7, 8}# use & operator# Output: {4, 5}print(A & B)
输出:
{4, 5}
在 Python Shell 中尝试以下程序:
# use intersection function on A>>> A.intersection(B){4, 5}# use intersection function on B>>> B.intersection(A){4, 5}
差集

Python 中的差集
集合B与集合A(A - B)的区别是仅在A中的一组元素,但不在B中。 类似地,B - A是B中的一组元素,但不是A中的一组元素。
使用-运算符进行区别。 使用difference()方法可以完成相同的操作。
# Difference of two sets# initialize A and BA = {1, 2, 3, 4, 5}B = {4, 5, 6, 7, 8}# use - operator on A# Output: {1, 2, 3}print(A - B)
输出:
{1, 2, 3}
在 Python Shell 中尝试以下程序:
# use difference function on A>>> A.difference(B){1, 2, 3}# use - operator on B>>> B - A{8, 6, 7}# use difference function on B>>> B.difference(A){8, 6, 7}
对称差集

Python 的对称差集
A和B的对称差异是A和B中的一组元素,但两者都不相同(不包括交叉点)。
对称差使用^运算符执行。 使用方法symmetric_difference()可以完成相同的操作。
# Symmetric difference of two sets# initialize A and BA = {1, 2, 3, 4, 5}B = {4, 5, 6, 7, 8}# use ^ operator# Output: {1, 2, 3, 6, 7, 8}print(A ^ B)
输出:
{1, 2, 3, 6, 7, 8}
在 Python Shell 中尝试以下程序:
# use symmetric_difference function on A>>> A.symmetric_difference(B){1, 2, 3, 6, 7, 8}# use symmetric_difference function on B>>> B.symmetric_difference(A){1, 2, 3, 6, 7, 8}
其他 Python 集方法
设置方法有很多,上面已经使用了其中的一些方法。 这是设置对象可用的所有方法的列表:
| 方法 | 描述 |
|---|---|
add() |
将元素添加到集合中 |
clear() |
从集合中删除所有元素 |
copy() |
返回集合的副本 |
difference() |
将两个或多个集合的差返回为新集合 |
difference_update() |
从该集合中删除另一个集合的所有元素 |
reject() |
如果元素是成员,则从集合中删除它。 (如果元素不在集合中,则不执行任何操作) |
intersection() |
返回两个集合的交集作为新集合 |
intersection_update() |
用自身和另一个的交集更新集合 |
isdisjoint() |
如果两个集合的交点为空,则返回True |
issubset() |
如果另一个集合包含此集合,则返回True |
issuperset() |
如果此集合包含另一个集合,则返回True |
pop() |
删除并返回一个任意集的元素。 如果集合为空,则升起KeyError |
remove() |
从集合中删除一个元素。 如果元素不是成员,则引发KeyError |
symmetric_difference() |
将两个集合的对称差作为新集合返回 |
symmetric_difference_update() |
用本身和另一个的对称差异更新一个集合 |
union() |
返回新集合中集合的并集 |
update() |
用自身和他人的并集更新集合 |
其他集操作
集的成员资格测试
我们可以使用in关键字来测试项目是否存在于集合中。
# in keyword in a set# initialize my_setmy_set = set("apple")# check if 'a' is present# Output: Trueprint('a' in my_set)# check if 'p' is present# Output: Falseprint('p' not in my_set)
输出:
TrueFalse
遍历集
我们可以使用for循环遍历集合中的每个项目。
>>> for letter in set("apple"):... print(letter)...apel
集的内置函数
诸如all(),any(),enumerate(),len(),max(),min(),sorted(),sum()等内置函数通常与集合一起使用以执行不同的任务。
| 函数 | Description |
| all() | 如果集合的所有元素都为true(或者集合为空),则返回True。 |
| any() | 如果集合中的任何元素为true,则返回True。 如果集合为空,则返回False。 |
| enumerate() | 返回一个枚举对象。 它包含该集合中所有项目的索引和值对。 |
| len() | 返回集合中的长度(项目数)。 |
| max() | 返回集合中最大的项目。 |
| min() | 返回集合中最小的项目。 |
| sorted() | 从集合中的元素返回一个新的排序列表(不对集合本身进行排序)。 |
| sum() | 返回集合中所有元素的总和。 |
Python Frozenset
Frozenset是具有集合特征的新类,但是一旦分配,就不能更改其元素。 元组是不可变列表,而冻结集是不可变集。
可变的集合不可散列,因此不能用作字典键。 另一方面,frozenset是可哈希化的,可用作字典的键。
可以使用Frozenset()函数创建Frozenset。
此数据类型支持copy(),difference(),intersection(),isdisjoint(),issubset(),issuperset(),symmetric_difference()和union()之类的方法。 由于是不可变的,因此没有添加或删除元素的方法。
# Frozensets# initialize A and BA = frozenset([1, 2, 3, 4])B = frozenset([3, 4, 5, 6])
在 Python shell 上尝试这些示例。
>>> A.isdisjoint(B)False>>> A.difference(B)frozenset({1, 2})>>> A | Bfrozenset({1, 2, 3, 4, 5, 6})>>> A.add(3)...AttributeError: 'frozenset' object has no attribute 'add'
