集合是项目的无序集合。每个集合元素都是唯一的(没有重复)并且必须是不可变的(不能更改)。
但是,集合本身是可变的。我们可以在其中添加或删除项目。
集合还可用于执行数学集合运算,例如并集、交集、对称差等。


创建 Python 集

通过将所有项目(元素)放在大括号内{},用逗号分隔或使用内置set()函数来创建集合。
它可以有任意数量的项目,它们可能是不同的类型(整数、浮点数、元组、字符串等)。但是集合不能将可变元素(如列表、集合或字典)作为其元素。

Different types of sets in Python # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, “Hello”, (1, 2, 3)} print(my_set)
输出
{1, 2, 3} {1.0, (1, 2, 3), ‘你好’}
也可以尝试以下示例。

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} 回溯(最近一次调用最后一次): 文件“”,第 15 行,在 中 my_set = {1, 2, [3, 4]} 类型错误:不可散列的类型:“列表”


创建一个空集有点棘手。
空花括号{}将在 Python 中创建一个空字典。为了创建一个没有任何元素的集合,我们使用set()没有任何参数的函数。

Distinguish set and dictionary while creating empty set # initialize a with {} a = {} # check data type of a print(type(a)) # initialize a with set() a = set() # check data type of a print(type(a))
输出
<类’集合’>


在 Python 中修改集合

集合是可变的。然而,由于它们是无序的,索引没有意义。
我们无法使用索引或切片访问或更改集合的元素。设置数据类型不支持。
我们可以使用该add()方法添加单个元素,也可以使用该方法添加多个元素update()。该update()方法可以将元组、列表、字符串或其他集合作为其参数。在所有情况下,都避免重复。

initialize my_set my_set = {1, 3} print(my_set) # my_set[0] # if you uncomment the above line # you will get an error # TypeError: ‘set’ object does not support indexing # 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_set my_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: KeyError my_set.remove(2)
输出
{1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5} 回溯(最近一次调用最后一次): 中的文件“”,第 28 行 密钥错误:2
同样,我们可以使用pop()方法删除并返回一个项目。
由于 set 是一种无序数据类型,因此无法确定将弹出哪个项目。这完全是任意的。
我们还可以使用clear()方法从集合中删除所有项目。

initialize my_set # Output: set of unique elements my_set = set(“HelloWorld”) print(my_set) # pop an element # Output: random element print(my_set.pop()) # pop another element my_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’} 放()


Python 集合操作

集合可用于执行数学集合运算,如并、交、差和对称差。我们可以使用运算符或方法来做到这一点。
让我们为以下操作考虑以下两组。
>>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8}

设置联合

image.png
在 Python 中设置联合
联盟 一种 和 乙 是来自两个集合的所有元素的集合。
联合是使用|运算符执行的。同样可以使用该union()方法来完成。

Set union method # initialize A and B A = {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}


设置交点

image.png
在 Python 中设置交集
的交集 一种 和 乙 是两个集合中共同的元素的集合。
使用&运算符执行交集。同样可以使用该intersection()方法来完成。

Intersection of sets # initialize A and B A = {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}


集差

image.png
在 Python 中设置差异
集合的不同 乙 从集合 一种(一种 —— 乙) 是一组仅在 一种 但不在 乙. 相似地,乙 —— 一种 是一组元素 乙 但不在 一种.
差异是使用-运算符进行的。同样可以使用该difference()方法来完成。

Difference of two sets # initialize A and B A = {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}


设置对称差

image.png
在 Python 中设置对称差异
的对称差 一种 和 乙 是一组元素 一种 和 乙 但不是在两者中(不包括交叉点)。
使用^运算符执行对称差分。同样可以使用方法来完成symmetric_difference()。

Symmetric difference of two sets # initialize A and B A = {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 集合方法

设置方法有很多,其中一些我们已经在上面使用过。以下是 set 对象可用的所有方法的列表:

方法 描述
添加() 向集合中添加一个元素
清除() 从集合中删除所有元素
复制() 返回集合的副本
区别() 将两个或多个集合的差作为新集合返回
差异更新() 从此集合中删除另一个集合的所有元素
丢弃() 如果元素是成员,则从集合中删除该元素。(如果元素未设置,则不执行任何操作)
路口() 返回两个集合的交集作为一个新集合
交叉更新() 用它自己和另一个的交集更新集合
isdisjoint() True如果两个集合有一个空交集,则返回
issubset() 返回True另一个集合是否包含此集合
issuperset() 返回True此集合是否包含另一个集合
流行音乐() 移除并返回一个任意的集合元素。KeyError如果集合为空则引发
消除() 从集合中移除一个元素。如果元素不是成员,则引发KeyError
对称差异() 将两个集合的对称差作为新集合返回
symmetry_difference_update() 用它自己和另一个的对称差异更新一个集合
联盟() 返回新集合中集合的并集
更新() 用它自己和其他人的并集更新集合

其他集合操作

设置会员测试

我们可以使用in关键字测试一个项目是否存在于集合中。

in keyword in a set # initialize my_set my_set = set(“apple”) # check if ‘a’ is present # Output: True print(‘a’ in my_set) # check if ‘p’ is present # Output: False print(‘p’ not in my_set)
输出
真的 错误的


迭代一个集合

我们可以使用循环遍历集合中的每个项目for。
>>> for letter in set(“apple”): … print(letter) … a p e l


带 Set 的内置函数

内置函数喜欢all(),any(),enumerate(),len(),max(),min(),sorted(),sum()等。通常与集用于执行不同的任务。

功能 描述
全部() 返回True如果集合中的所有元素都为真(或者,如果设置为空)。
任何() True如果集合中的任何元素为真,则返回。如果集合为空,则返回False。
枚举() 返回一个枚举对象。它包含集合中所有项目的索引和值作为一对。
长度() 返回集合中的长度(项目数)。
最大限度() 返回集合中最大的项目。
分钟() 返回集合中最小的项。
排序() 从集合中的元素返回一个新的排序列表(不对集合本身进行排序)。
和() 返回集合中所有元素的总和。

Python 冻结集

Frozenset 是一个新的类,它具有集合的特性,但它的元素一旦赋值就不能改变。元组是不可变的列表,而frozensets 是不可变的集合。
可变的集合是不可散列的,因此它们不能用作字典键。另一方面,frozensets 是可散列的,可以用作字典的键。
可以使用frozenset()函数创建冻结集
此数据类型支撑件的方法,如copy(),difference(),intersection(),isdisjoint(),issubset(),issuperset(),symmetric_difference()和union()。由于不可变,它没有添加或删除元素的方法。
# Frozensets # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6])
在 Python shell 上尝试这些示例。
>>> A.isdisjoint(B) False >>> A.difference(B) frozenset({1, 2}) >>> A | B frozenset({1, 2, 3, 4, 5, 6}) >>> A.add(3) … AttributeError: ‘frozenset’ object has no attribute ‘add’