
5.2 集合
集合与元组和列表实际上也是接近的,只是集合强调的是元素的无序性和唯一性,也就是说,集合中的元素是没有固定排序的,并且一个集合中不存在两个相同的元素。
5.2.1 创建集合
创建集合使用的是花括号“{}”或Python的内置函数set,下面通过如代码清单5-6来说明。
代码清单5-6:创建集合

显然,创建集合还是比较简单的,但是如果创建的是一个空集合,那么只能使用set函数,而不能使用花括号,如下所示:

运行上述代码得到的输出结果如下:

由此可见,这里的set2并不是一个集合,而是后面要介绍的字典,所以创建空集合只能使用set函数,而不能使用花括号。
对于集合来说,元素是不能重复的,如果在创建时存在相同的元素,那么集合会自动合并,以保证每个元素都不同,代码清单5-7可以验证这一点。
代码清单5-7:带有重复元素创建集合

上述代码中的“python”、3和9都是重复的元素,在创建的时候集合会将它们合并为一个,因此运行这段程序的输出结果如下:

由此可见,集合会合并相同的元素,以保证每个元素都是不重复的。
5.2.2 新增元素
在集合中新增元素可以使用add函数和update函数。其中,使用add函数可以新增一个元素,而使用update函数可以将元组、集合、列表等可迭代的数据类型的元素添加到集合中。
add函数的用法如下:

显然,add函数允许一个一个地新增元素。如果需要添加多个元素则可以考虑使用update函数,如下所示:


运行上述代码得到的输出结果如下:

每次运行的输出结果都可能出现不同,这是因为集合中的元素是无序的,并不能保证元素的顺序。
注意 当update函数的参数为字符串类型时
上面没有在update函数的参数中使用字符串,因为使用字符串需要特别注意,所以这里单独介绍。update函数的参数使用字符串的代码如下:

运行上述代码可能会(这是因为集合中的元素是无序的)得到如下输出结果:

由此可见,update函数会将字符串中的一个个字符作为元素存放到集合中。所以,需要给集合添加元素在遇到字符串时,如果是一个字符串那么最好使用add函数,如果是多个字符串则可以使用列表、集合和元组等,如下所示:

5.2.3 删除元素
在集合中存在3个删除元素的函数,分别是remove、discard和pop,下面展开介绍。
remove函数代表删除一个元素,参数是元素的值,需要注意的是,当无法找到对应的元素时,运行时会发生异常,如下所示:

需要注意的是,代码①处删除的5并不在集合中,所以运行到这行时就会发生异常,为了保证不发生异常,就需要先行验证元素是否在集合中,如下所示:

但是这样会显得很麻烦,为此集合中还提供了discard函数。discard函数的含义也是删除集合中的一个元素,但是如果找不到要删除的元素,那么就什么都不做,这样就不会发生异常,如下所示:

上述代码使用了discard函数,这样即使运行到代码①处时,集合也不会因为找不到元素而发生异常。
pop函数则是从集合中随机弹出一个元素,之所以是随机的,是因为集合是无序的。如果集合已经为空,那么pop函数在执行时也会发生异常。下面通过代码清单5-8来说明。
代码清单5-8:使用集合中的pop函数

需要注意代码①处,由于set2是一个空集合,因此执行这行代码时会发生异常。
此外,集合中还提供了清空的功能,clear函数可以清空集合中所有的元素,如下所示:

运行上述代码得到的输出结果如下:

5.2.4 判断元素是否在集合中
判断元素是否在集合中使用in关键字,这和列表、元组等数据类型也是接近的,如下所示:

运行上述代码得到的输出结果如下:

5.2.5 遍历集合
对于集合来说,它的元素是无序的,所以遍历集合时,元素的顺序也是随机的。遍历集合的方法很多,下面通过代码清单5-9来说明。
代码清单5-9:遍历集合中的元素

代码①处使用for循环遍历集合,代码②处通过迭代来进行循环,代码③处则是通过while循环遍历集合。运行上述代码可能会输出如下结果:

注意 时刻需要注意的是集合中的元素是无序的
如果多次运行代码清单5-9,读者就会发现运行结果可能会有所不同,这是因为集合中的元素是无序的,Python并不保证集合元素的顺序。如果需要有序的元素,那么可以使用列表,只是列表并不保证元素的唯一性。
5.2.6 关于集合的函数
关于集合的函数,首先是Python内置的4个函数,如表5-2所示。
表5-2 Python内置的4个函数

下面运用表5-2中的4个函数,如代码清单5-10所示。
代码清单5-10:Python关于集合的4个内置函数

运行上述代码得到的输出结果如下:

除此之外,集合也有自己的函数,主要是集合交、补、并、差等运算,下面通过表5-3进行简要的说明。
表5-3 集合的相关函数

在表5-3中,加粗的函数在前面已经讨论过,所以本节不再重复介绍。其他的函数则是读者需要关注的内容,主要是集合的交、补、并、差运算,下面通过举例进行介绍。
copy函数用于复制当前的集合,测试代码如下:

运行上述代码得到的输出结果如下:

虽然复制集合成功,但两个集合的地址不尽相同,这说明复制会创建新的集合。
差集主要使用函数difference和difference_update,它们的逻辑是相同的,只是difference_update函数会更新当前集合中的元素,而difference函数则不会,测试代码如下:

difference函数和difference_update函数的区别在于是否会修改当前集合中的元素,这是需要读者在实践中注意的。运行上述代码得到的输出结果如下:

交集分为3个函数:isdisjoint、intersection和intersection_update。isdisjoint函数用于判断两个集合是否存在相交的元素;intersection函数用于求两个集合的交集,但是并不改变当前集合;intersection_update函数用于求两个集合的交集并修改当前集合。测试代码如下:

运行上述代码得到的输出结果如下:

接下来求集合中不重复的元素,这里涉及两个函数:symmetric_difference和symmetric_difference_update。其中,symmetric_difference函数会返回两个集合中不重复的元素,而symmetric_difference_update函数则用于求两个集合中不重复的元素,并赋值给当前集合。下面通过代码进行说明:

运行上述代码得到的输出结果如下:

下面进行父子集合的判断,这里涉及两个函数:issubset和issuperset。issubset函数用于判断当前集合是否为参数集合的子集,而issuperset函数则用于判断当前集合是否为参数集合的父集。下面通过代码进行说明:

运行上述代码得到的输出结果如下:

最后介绍并集,它只有一个union函数,下面举例说明:

运行上述代码得到的输出结果如下:
