首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【七】Python基础之数据结构:集合

【七】Python基础之数据结构:集合

作者头像
菲宇
发布2019-06-13 10:54:35
3820
发布2019-06-13 10:54:35
举报
文章被收录于专栏:菲宇菲宇

定义:

1.不同元素组成,元素不能重复

2.无序

3.集合中的元素必须是不可变类型

创建集合

1

s = {1,2,3,4,5,6,7,8}

1.定义可变集合

1 2 3

>>> set_test = set('hello') >>> set_test {'h', 'l', 'e', 'o'}

2.定义不可变集合

1 2 3 4 5 6

>>> set_test = set('hello') >>> set_test {'h', 'l', 'e', 'o'}  # 由此可见集合中的元素不可重复,都是不同的 >>> n_set_test = frozenset(set_test) >>> n_set_test frozenset({'h', 'l', 'e', 'o'})

集合运算

集合之间也可进行数学集合运算(例如:并集、交集等),可用相应的操作符或方法来实现。

子集

  子集,为某个集合中一部分的集合,故亦称部分集合。

  使用操作符 < 执行子集操作,同样地,也可使用方法 issubset() 完成。

1 2 3 4 5 6 7 8 9

>>> A = set('abcd') >>> B = set('cdef') >>> C = set("ab") >>> C < A True # C 是 A 的子集 >>> C < B False >>> C.issubset(A) True

并集 

  一组集合的并集是这些集合的所有元素构成的集合,而不包含其他元素。

  使用操作符 | 执行并集操作,同样地,也可使用方法 union() 完成。

1 2 3 4

>>> A | B {'c', 'b', 'f', 'd', 'e', 'a'} >>> A.union(B) {'c', 'b', 'f', 'd', 'e', 'a'}

交集

  两个集合 A 和 B 的交集是含有所有既属于 A 又属于 B 的元素,而没有其他元素的集合。

  使用 & 操作符执行交集操作,同样地,也可使用方法 intersection() 完成。

1 2 3 4

>>> A & B {'c', 'd'} >>> A.intersection(B) {'c', 'd'}

差集

  A 与 B 的差集是所有属于 A 且不属于 B 的元素构成的集合

  使用操作符 - 执行差集操作,同样地,也可使用方法 difference() 完成。

1 2 3 4

>>> A - B {'b', 'a'} >>> A.difference(B) {'b', 'a'}

对称差

  两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合。

  使用 ^ 操作符执行差集操作,同样地,也可使用方法 symmetric_difference() 完成。

1 2 3 4

>>> A ^ B {'b', 'f', 'e', 'a'} >>> A.symmetric_difference(B) {'b', 'f', 'e', 'a'}

集合方法

1.add 向集合中添加元素

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> s.add("s") >>> s {1, 2, 3, 4, 5, 6, 's'}

2.clear 清空集合

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> s.clear() >>> s set()

3.copy 返回集合的浅拷贝

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> new_s = s.copy() >>> new_s {1, 2, 3, 4, 5, 6}

4.pop 删除并返回任意的集合元素(如果集合为空,会引发 KeyError)

1 2 3 4 5

>>> s = {1, 2, 3, 4, 5, 6} >>> s.pop()  # pop删除时是无序的随机删除 1 >>> s {2, 3, 4, 5, 6}

5.remove 删除集合中的一个元素(如果元素不存在,会引发 KeyError)

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> s.remove(3) >>> s {1, 2, 4, 5, 6}

6.discard 删除集合中的一个元素(如果元素不存在,则不执行任何操作)

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> s.discard("sb") >>> s {1, 2, 3, 4, 5, 6}

7.intersection 将两个集合的交集作为一个新集合返回

1 2 3 4 5 6

>>> s = {1, 2, 3, 4, 5, 6} >>> s2 = {3, 4, 5, 6, 7, 8} >>> s.intersection(s2) {3, 4, 5, 6} >>> s&s2  # 可以达到相同的效果 {3, 4, 5, 6}

8.union 将集合的并集作为一个新集合返回

1 2 3 4 5 6

>>> s = {1, 2, 3, 4, 5, 6} >>> s2 = {3, 4, 5, 6, 7, 8} >>> print(s.union(s2)) {1, 2, 3, 4, 5, 6, 7, 8} >>> print(s|s2) # 用 | 可以达到相同效果 {1, 2, 3, 4, 5, 6, 7, 8}

9.difference 将两个或多个集合的差集作为一个新集合返回 

1 2 3 4 5 6 7 8 9 10

>>> s = {1, 2, 3, 4, 5, 6} >>> s2 = {3, 4, 5, 6, 7, 8} >>> print("差集:",s.difference(s2)) # 去除s和s2中相同元素,删除s2 保留s中剩余元素 差集: {1, 2} >>> print("差集:",s2.difference(s))  # 去除s和s2中相同元素,删除s2 保留s2中剩余元素<br> 差集: {8, 7} >>> print("差集:",s - s2) # 符号 - 可以达到相同结果 差集: {1, 2} >>> print("差集:",s2 - s) # 符号 - 可以达到相同结果 差集: {8, 7}

10. symmetric_difference 将两个集合的对称差作为一个新集合返回(两个集合合并删除相同部分,其余保留) 

1 2 3 4

>>> s = {1, 2, 3, 4, 5, 6} >>> s2 = {3, 4, 5, 6, 7, 8} >>> s.symmetric_difference(s2) {1, 2, 7, 8}

11.update 用自己和另一个的并集来更新这个集合

1 2 3 4 5 6 7

>>> s = {'p', 'y'} >>> s.update(['t', 'h', 'o', 'n']) # 添加多个元素 >>> s {'p', 't', 'o', 'y', 'h', 'n'} >>> s.update(['H', 'e'], {'l', 'l', 'o'}) # 添加列表和集合 >>> s {'p', 'H', 't', 'l', 'o', 'y', 'e', 'h', 'n'}

12.intersection_update() 用自己和另一个的交集来更新这个集合

1 2 3 4 5

>>> s = {'a', 'b', 'c', 'd', 'q'} >>> s2 = {'c', 'd', 'e', 'f'} >>> s.intersection_update(s2) # 相当于s = s - s2 >>> s {'c', 'd'}

13.isdisjoint()  如果两个集合有一个空交集,返回 True

1 2 3 4 5 6 7

>>> s = {1, 2} >>> s1 = {3, 4} >>> s2 = {2, 3} >>> s.isdisjoint(s1) True # s 和 s1 两个集合的交集为空返回 True >>> s.isdisjoint(s2) False # s 和 s2 两个集合的交集为 2 不是空 所有返回False

14.issubset() 如果另一个集合包含这个集合,返回 True

1 2 3 4 5 6 7

>>> s = {1, 2, 3} >>> s1 = {1, 2, 3, 4} >>> s2 = {2, 3} >>> s.issubset(s1) True # 因为 s1 集合 包含 s 集合 >>> s.issubset(s2) False # s2 集合 不包含 s 集合

15.issuperset()  如果这个集合包含另一个集合,返回 True

1 2 3 4 5 6 7

>>> s = {1, 2, 3} >>> s1 = {1, 2, 3, 4} >>> s2 = {2, 3} >>> s.issuperset(s1) False # s 集合不包含 s1 集合 >>> s.issuperset(s2) True # s 集合包含 s2 集合

16.difference_update() 从这个集合中删除另一个集合的所有元素

1 2 3 4 5 6 7 8 9

>>> s = {1, 2, 3} >>> s1 = {1, 2, 3, 4} >>> s2 = {2, 3} >>> s.difference_update(s2) >>> s {1} # s2中的2,3 s集合中也有2,3 所以保留1 >>> s1.difference_update(s2) >>> s1 {1, 4}

17.symmetric_difference_update() 用自己和另一个的对称差来更新这个集合

1 2 3 4 5 6 7 8 9 10 11 12

>>> s = {1, 2, 3} >>> s1 = {1, 2, 3, 4} >>> s2 = {2, 3} >>> s1.symmetric_difference_update(s) >>> s1 {4} >>> s1.symmetric_difference_update(s2) >>> s1 {2, 3, 4} >>> s.symmetric_difference_update(s2) >>> s {1}

集合内置方法

方法

描述

add()

为集合添加元素

clear()

移除集合中的所有元素

copy()

拷贝一个集合

difference()

返回多个集合的差集

difference_update()

移除集合中的元素,该元素在指定的集合也存在。

discard()

删除集合中指定的元素

intersection()

返回集合的交集

intersection_update()

删除集合中的元素,该元素在指定的集合中不存在。

isdisjoint()

判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。

issubset()

判断指定集合是否为该方法参数集合的子集。

issuperset()

判断该方法的参数集合是否为指定集合的子集

pop()

随机移除元素

remove()

移除指定元素

symmetric_difference()

返回两个集合中不重复的元素集合。

symmetric_difference_update()

移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。

union()

返回两个集合的并集

update()

给集合添加元素

集合与内置函数

下述内置函数通常作用于集合,来执行不同的任务。

函数

描述

all()

如果集合中的所有元素都是 True(或者集合为空),则返回 True。

any()

如果集合中的所有元素都是 True,则返回 True;如果集合为空,则返回 False。

enumerate()

返回一个枚举对象,其中包含了集合中所有元素的索引和值(配对)。

len()

返回集合的长度(元素个数)

max()

返回集合中的最大项

min()

返回集合中的最小项

sorted()

从集合中的元素返回新的排序列表(不排序集合本身)

sum()

返回集合的所有元素之和

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
     
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set,添加元素
         
        This has no effect if the element is already present.
        """
        pass
 
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. 清除内容"""
        pass
 
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. 浅拷贝  """
        pass
 
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set. A中存在,B中不存在
         
        (i.e. all elements that are in this set but not the others.)
        """
        pass
 
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
        pass
 
    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.
         
        If the element is not a member, do nothing. 移除指定元素,不存在不保错
        """
        pass
 
    def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set. 交集
         
        (i.e. all elements that are in both sets.)
        """
        pass
 
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
        pass
 
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
        pass
 
    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set.  是否是子序列"""
        pass
 
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. 是否是父序列"""
        pass
 
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty. 移除元素
        """
        pass
 
    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.
         
        If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
        """
        pass
 
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.  对称差集
         
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
 
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
        pass
 
    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.  并集
         
        (i.e. all elements that are in either set.)
        """
        pass
 
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. 更新 """
        pass
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年12月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 定义:
    • 创建集合
      • 集合运算
        • 子集
        • 并集 
        • 交集
        • 差集
        • 对称差
        • 集合内置方法
      • 集合与内置函数
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档