Python组合数据类型——集合类型:集合

简介: Python内置数据结构之一,与列表,字典一样都属于可变序列,集合是没有value的字典,集合中的元素是无序的,元素不可以重复。

一、什么是集合

  1. Python内置数据结构之一
  2. 与列表,字典一样都属于可变序列
  3. 集合是没有value的字典
  4. 集合中的元素是无序的,元素不可以重复

1.集合操作符

操作符的运算 描述
S-T 返回一个新集合,包括在集合S中但不会在集合T
S&T 返回一个新集合,包括同时在集合ST中的元素
S^T 返回一个新集合,包括ST中的非共同元素
`S\ T` 返回一个新集合,包括集合ST中的所有元素

2.常用集合操作函数或方法

函数或方法 描述
S.add(x) 如果数据项x不在S中,将x增加到S
S.remove(x) 如果x集合在S中,移除该元素;不在则产生KeyError异常
S.clear() 移除S中的数据项
len(S) 返回集合S的元素个数
x in S 如果xs的元素,返回True;否则返回False
x not in S 如果xs的元素,返回True;否则返回False

3.内置数据结构set源码

Python内置数据结构集合类class set(object)源码解析:

class set(object):  # set类
    """
           set() ->新的空集合对象
        set (iterable) ->新设置对象
        构建独特元素的无序集合。
    """
    def add(self, *args, **kwargs): # real signature unknown
        """
        向集合中添加一个元素。
        如果该元素已经存在,则不会产生任何影响。
        """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ 从这个集合中删除所有元素。 """
        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
        """
        返回两个或多个集合的差值作为新集合。
        (即所有在这个集合中的元素,而不是其他集合中的元素。)
        """
        pass

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ 从这个集合中删除另一个集合的所有元素 """
        pass

    def discard(self, *args, **kwargs): # real signature unknown
        """
        从集合中移除一个元素,如果它是成员。
        如果元素不是成员,则不执行任何操作。
        """
        pass

    def intersection(self, *args, **kwargs): # real signature unknown
        """
        返回两个集合的交集作为新集合。
        (即两个集合中的所有元素。)
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): # real signature unknown
        """ 报告另一个集合是否包含此集合。 """
        pass

    def issuperset(self, *args, **kwargs): # real signature unknown
        """ 报告此集合是否包含另一个集合。 """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """
        删除并返回任意的set元素。
        如果该集合为空则引发KeyError。
        """
        pass

    def remove(self, *args, **kwargs): # real signature unknown
        """
        从集合中移除一个元素;它必须是成员。
        如果元素不是成员,则引发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. """
        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
        """ 使用自身和其他集合的并集更新集合。 """
        pass

    def __and__(self, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iand__(self, *args, **kwargs): # real signature unknown
        """ Return self&=value. """
        pass

    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        
        Build an unordered collection of unique elements.
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs): # real signature unknown
        """ Return self|=value. """
        pass

    def __isub__(self, *args, **kwargs): # real signature unknown
        """ Return self-=value. """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __ixor__(self, *args, **kwargs): # real signature unknown
        """ Return self^=value. """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass

    __hash__ = None

二、集合的创建方式

1. 使用 {}

s = {1, 2, 3, 4, 5, 6, 6}
print(s)
# {1, 2, 3, 4, 5, 6}

2. 使用内置函数 set()

s1 = set(range(1, 7))
print(s1)
# {1, 2, 3, 4, 5, 6}
print(set('python'))
# {'p', 'h', 'n', 'o', 't', 'y'}

三、集合的相关操作

1.集合元素的判断操作

操作函数 描述
a in s 如果as的元素,返回True;否则返回False
a not in s 如果 a不是s的元素,返回True;否则返回False
# 判断元素是否在集合中
s = {10, 20, 30, 40, 50, 100}
print(10 in s)  # True
print(10 not in s)  # False

2.集合的新增操作

# 集合元素的新增操作
s = {10, 20, 30, 40, 50, 100}
s.add(80)  # 添加一个元素
print(s)  
# {100, 40, 10, 80, 50, 20, 30}
s.update({66, 77, 88})  # 添加多个元素(一次至少添加一个元素 )
print(s)
# {66, 100, 40, 10, 77, 80, 50, 20, 88, 30}
s.update((11, 22, 33))
print(s)
# {33, 66, 100, 40, 10, 11, 77, 80, 50, 20, 22, 88, 30}

3.集合的删除操作

# 集合元素的删除操作
#  1.调用remove方法,一次删除一个指定元素,元素不存在抛异常
s.remove(100)
print(s)
# {33, 66, 40, 10, 11, 77, 80, 50, 20, 22, 88, 30}

# 2.调用discard方法,一次删除一个指定元素,元素不存在不抛异常
s.discard(300)
print(s)
# {33, 66, 40, 10, 11, 77, 80, 50, 20, 22, 88, 30}

# 3.调用pop方法,一次只删除一个任意元素
s.pop()
print(s)
# {66, 40, 10, 11, 77, 80, 50, 20, 22, 88, 30}

# 4.调用clear方法,清空集合
s.clear()
print(s)
# set()
相关文章
|
6天前
|
存储 索引 Python
Python散列类型(1)
【10月更文挑战第9天】
|
11天前
|
计算机视觉 Python
Python实用记录(一):如何将不同类型视频按关键帧提取并保存图片,实现图片裁剪功能
这篇文章介绍了如何使用Python和OpenCV库从不同格式的视频文件中按关键帧提取图片,并展示了图片裁剪的方法。
38 0
|
4天前
|
存储 数据安全/隐私保护 索引
|
10天前
|
Python
【10月更文挑战第7天】「Mac上学Python 13」基础篇7 - 数据类型转换与NoneType详解
本篇将详细介绍Python中的常见数据类型转换方法以及 `NoneType` 的概念。包括如何在整数、浮点数、字符串等不同数据类型之间进行转换,并展示如何使用 `None` 进行初始赋值和处理特殊情况。通过本篇的学习,用户将深入理解如何处理不同类型的数据,并能够在代码中灵活使用 `None` 处理未赋值状态。
47 2
【10月更文挑战第7天】「Mac上学Python 13」基础篇7 - 数据类型转换与NoneType详解
|
11天前
|
Python
【10月更文挑战第6天】「Mac上学Python 11」基础篇5 - 字符串类型详解
本篇将详细介绍Python中的字符串类型及其常见操作,包括字符串的定义、转义字符的使用、字符串的连接与格式化、字符串的重复和切片、不可变性、编码与解码以及常用内置方法等。通过本篇学习,用户将掌握字符串的操作技巧,并能灵活处理文本数据。
46 1
【10月更文挑战第6天】「Mac上学Python 11」基础篇5 - 字符串类型详解
|
11天前
|
Python
【10月更文挑战第6天】「Mac上学Python 10」基础篇4 - 布尔类型详解
本篇将详细介绍Python中的布尔类型及其应用,包括布尔值、逻辑运算、关系运算符以及零值的概念。布尔类型是Python中的一种基本数据类型,广泛应用于条件判断和逻辑运算中,通过本篇的学习,用户将掌握如何使用布尔类型进行逻辑操作和条件判断。
46 1
【10月更文挑战第6天】「Mac上学Python 10」基础篇4 - 布尔类型详解
WK
|
5天前
|
存储 Python
Python内置类型名
Python 内置类型包括数字类型(int, float, complex)、序列类型(str, list, tuple, range)、集合类型(set, frozenset)、映射类型(dict)、布尔类型(bool)、二进制类型(bytes, bytearray, memoryview)、其他类型(NoneType, type, 函数类型等),提供了丰富的数据结构和操作,支持高效编程。
WK
9 2
|
7天前
|
存储 编译器 索引
Python 序列类型(2)
【10月更文挑战第8天】
Python 序列类型(2)
|
8天前
|
存储 C++ 索引
Python 序列类型(1)
【10月更文挑战第8天】
|
13天前
|
编译器 数据安全/隐私保护 Python
Python--基本数据类型
【10月更文挑战第4天】