12.5、python基础数据类型(set集合)

简介: 基础数据类型(set集合)认识集合  由一个或多个确定的元素所构成的整体叫做集合。  集合中的元素有三个特征:    1.确定性(集合中的元素必须是确定的)    2.互异性(集合中的元素互不相同。

基础数据类型(set集合)

认识集合

  由一个或多个确定的元素所构成的整体叫做集合。

  集合中的元素有三个特征:

    1.确定性(集合中的元素必须是确定的)

    2.互异性(集合中的元素互不相同。例如:集合A={1,a},则a不能等于1)

    3.无序性(集合中的元素没有先后之分),如集合{3,4,5}和{3,5,4}算作同一个集合。

  *集合概念存在的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中某个值

集合的定义

  s = {1,2,3,1}

#定义可变集合>>> set_test=set('hello')

>>> set_test

{'l', 'o', 'e', 'h'}#改为不可变集合frozenset>>> f_set_test=frozenset(set_test)

>>> f_set_test

frozenset({'l', 'e', 'h', 'o'})

集合的常用操作及关系运算

  元素的增加

  单个元素的增加 : add(),add的作用类似列表中的append

  对序列的增加 : update(),而update类似extend方法,update方法可以支持同时传入多个参数:

>>> a={1,2}

>>> a.update([3,4],[1,2,7])

>>> a

{1, 2, 3, 4, 7}

>>> a.update("hello")

>>> a

{1, 2, 3, 4, 7, 'h', 'e', 'l', 'o'}

>>> a.add("hello")

>>> a

{1, 2, 3, 4, 'hello', 7, 'h', 'e', 'l', 'o'}

  元素的删除

  集合删除单个元素有两种方法:

    元素不在原集合中时:

      set.discard(x)不会抛出异常

      set.remove(x)会抛出KeyError错误

>>> a={1,2,3,4}

>>> a.discard(1)

>>> a

{2, 3, 4}

>>> a.discard(1)

>>> a

{2, 3, 4}

>>> a.remove(1)

Traceback (most recent call last):

  File "<input>", line 1, in <module>

KeyError: 1

  pop():由于集合是无序的,pop返回的结果不能确定,且当集合为空时调用pop会抛出KeyError错误,

  clear():清空集合

>>> a={3,"a",2.1,1}

>>> a.pop()

1

>>> a.pop()

3

>>> a.clear()

>>> a

set()

>>> a.pop()

Traceback (most recent call last):

  File "<input>", line 1, in <module>

KeyError: 'pop from an empty set'

  集合操作


img_b6015fdc0679f768d95104ffd6fd18ff.jpe

    |,|=:合集

a = {1,2,3}

b = {2,3,4,5}print(a.union(b))print(a|b)

    &.&=:交集

a = {1,2,3}

b = {2,3,4,5}print(a.intersection(b))print(a&b)

    -,-=:差集

a = {1,2,3}

b = {2,3,4,5}print(a.difference(b))print(a-b) 

    ^,^=:对称差集

a = {1,2,3}

b = {2,3,4,5}print(a.symmetric_difference(b))print(a^b)


  包含关系

    in,not in:判断某元素是否在集合内

    ==,!=:判断两个集合是否相等

    两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

set.isdisjoint(s):判断两个集合是不是不相交

set.issuperset(s):判断集合是不是包含其他集合,等同于a>=b

set.issubset(s):判断集合是不是被其他集合包含,等同于a<=b

集合的工厂函数

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        """

        相当于s1-s2


        Return the difference of two or more sets as a new set.


        (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. """        pass    def discard(self, *args, **kwargs): # real signature unknown        """

        与remove功能相同,删除元素不存在时不会抛出异常


        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        """

        相当于s1&s2


        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. """        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        """

        相当于s1<=s2


        Report whether another set contains this set. """        pass    def issuperset(self, *args, **kwargs): # real signature unknown        """

        相当于s1>=s2


        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        """

        相当于s1^s2


        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        """

        相当于s1|s2


        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    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

目录
相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
726 2
|
存储 JSON 算法
Python集合:高效处理无序唯一数据的利器
Python集合是一种高效的数据结构,具备自动去重、快速成员检测和无序性等特点,适用于数据去重、集合运算和性能优化等场景。本文通过实例详解其用法与技巧。
453 0
|
存储 索引 Python
python 集合的所有基础知识
python 集合的所有基础知识
1402 0
|
存储 Java 索引
(Python基础)新时代语言!一起学习Python吧!(二):字符编码由来;Python字符串、字符串格式化;list集合和tuple元组区别
字符编码 我们要清楚,计算机最开始的表达都是由二进制而来 我们要想通过二进制来表示我们熟知的字符看看以下的变化 例如: 1 的二进制编码为 0000 0001 我们通过A这个字符,让其在计算机内部存储(现如今,A 字符在地址通常表示为65) 现在拿A举例: 在计算机内部 A字符,它本身表示为 65这个数,在计算机底层会转为二进制码 也意味着A字符在底层表示为 1000001 通过这样的字符表示进行转换,逐步发展为拥有127个字符的编码存储到计算机中,这个编码表也被称为ASCII编码。 但随时代变迁,ASCII编码逐渐暴露短板,全球有上百种语言,光是ASCII编码并不能够满足需求
526 4
|
机器学习/深度学习 数据采集 并行计算
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
1241 2
|
Python
Python技术解析:了解数字类型及数据类型转换的方法。
在Python的世界里,数字并不只是简单的数学符号,他们更多的是一种生动有趣的语言,用来表达我们的思维和创意。希望你从这个小小的讲解中学到了有趣的内容,用Python的魔法揭示数字的奥秘。
382 26
|
人工智能 Python
python基本数据类型简介
本文简要介绍了Python的基本数据类型,包括整型、浮点型、字符串、列表、字典和布尔类型,帮助读者对Python数据类型有初步了解。
386 0
|
Python
探索Python的各式数据类型
以上就是Python数据类型的一次简单而有趣的游览。和她继续接触,你会发现她还有更多有趣的面象,例如集合里的冰冻集合(Frozenset),序列里的字符串(String)和字节序列(Bytes)等等。希望这次游览能对你有所启发,让你更好地理解和使用Python。
236 21
|
存储 安全 开发者
Python中的数据类型详解
Python是一种动态类型编程语言,具备丰富的数据类型,包括数值类型、序列类型、映射类型和集合类型等。这些类型为高效编程提供了强大支持。
398 0
|
存储 缓存 安全
Python frozenset 集合详解:不可变集合的终极指南
frozenset是Python中一个常被忽视但极具价值的不可变集合类型。本文深入解析其本质、操作方法与应用场景,揭示其通过不可变性带来的安全性与性能优势。从底层实现到实战案例,涵盖字典键使用、缓存优化及类型注解等高级场景。同时对比性能数据,提供最佳实践指南,并展望Python 3.11+中的优化。掌握frozenset,可为代码带来更强健性与效率,适合多种特定需求场景。
698 5

热门文章

最新文章

推荐镜像

更多