腾讯课堂——基础数据类型(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‘  

  集合操作

    |,|=:合集

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

set

课程回顾:

    腾讯课堂第一课——流程控制 :https://www.cnblogs.com/l-hf/p/11528934.html

    腾讯课堂第二课——循     环 :https://www.cnblogs.com/l-hf/p/11528937.html

    腾讯课堂第三课——数字和字符串  : https://www.cnblogs.com/l-hf/p/11528845.html

    腾讯课堂第四课——列    表  : https://www.cnblogs.com/l-hf/p/11528858.html

    腾讯课堂第四课——字    典  :https://www.cnblogs.com/l-hf/p/11528867.html

    腾讯课堂第五课——元    祖  :https://www.cnblogs.com/l-hf/p/11528864.htmll

更多相关内容,详见:

     Python全栈开发入门经典:https://ke.qq.com/course/157698#tuin=839b573b

     Python全栈开发进阶实战:https://ke.qq.com/course/158006#tuin=839b573b

  

原文地址:https://www.cnblogs.com/l-hf/p/11528953.html

时间: 2024-10-09 06:09:22

腾讯课堂——基础数据类型(set集合)的相关文章

腾讯课堂——基础数据类型(dict字典)

初识字典 标准类型 数字 字符串 列表 字典 元组 字典是Python语言中唯一的映射类型. 定义:{key1:value1,key2:value2}    1.键与值用冒号":"分开:    2.项与项用逗号","分开: 特性:  1.key-value结构    2.key必须可hash.且必须为不可变数据类型.必须唯一    3.可存放任意多个值.可修改.可以不唯一    4.无序 字典的创建 person = {"name": "

腾讯课堂——基础数据类型(tuple元祖)

初识元祖 标准类型 数字 字符串 列表 字典 元组 定义:与列表类似,只不过[]改成() 特性: 1.可存放多个值 2.不可变 3.按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序 元祖的创建 ages = (11, 22, 33, 44, 55) 或 ages = tuple((11, 22, 33, 44, 55)) 顺序及下标图示 元祖的常用操作 索引 切片 循环 长度 包含 元祖的特性详解 1.可存放多个值 如果元祖中只有一个值 t = (1,) t = (1) #<==>t

Py西游攻关之基础数据类型(五)-集合

Py西游攻关之基础数据类型 - Yuan先生 https://www.cnblogs.com/yuanchenqi/articles/5782764.html 八 集合(set) 集合是一个无序的,不重复的数据组合,它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 集合(set):把不同的元素组成一起形成集合,是python基本的数据类型. 集合元素(set elements):组成集合的成员(不可重复) li=[1,2,'a','b

基础数据类型之集合和深浅copy,还有一些数据类型补充

集合 集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的.以下是集合最重要的两点: 去重,把一个列表变成集合,就自动去重了. 关系测试,测试两组数据之前的交集.差集.并集等关系. #关于集合和波尔值之间的苟苟且且# set ={1,2,3,4,5,True,(1,2,3),} #集合具有自动去重和去空格功能# set.add(False)# set.add(True) #打印结果显示,没有Teue,应该是集合内部的数字和元组不

基础数据类型{set集合}

一.集合 set集合是python的?个基本数据类型. ?般不是很常?. set中的元素是不重复的.?序的.??的元素必须是可hash的(int, str, tuple,bool), 我们可以这样来记. set就是dict类型的数据但是不保存value, 只保存key. set也?{}表? 注意: set集合中的元素必须是可hash的, 但是set本?是不可hash得. set是可变的. set1 = {'1','alex',2,True,[1,2,3]} # 报错set2 = {'1','al

WPF ListView绑定基础数据类型集合

ListView中前台数据源绑定基础数据类型集合时没有Path名称,例如直接绑定List<string>,List<int>,BingdingList<string>等,此时直接使用{Bingding Path=.}即可 <ListView.View> <GridView> <GridViewColumn Header="HeaderName" > <GridViewColumn.CellTemplate&g

python基础(9):基本数据类型四(set集合)、基础数据类型补充、深浅拷贝

1. 基础数据类型补充 li = ["李嘉诚", "麻花藤", "?海峰", "刘嘉玲"] s = "_".join(li) print(s) li = "?花?闺?" s = "_".join(li) print(s) 列表: 循环删除列表中的每?个元素 li = [11, 22, 33, 44] for e in li: li.remove(e) print(li

Python之路【第四篇】python基础 之基本数据类型之集合

基本数据类型之集合 set set集合,是一个无序且不重复的元素集合 1 # set 不允许重复的集合 set允许重复的列表但是集合是无序的 2 #例如 3 # s = {1,23,23,4,55,55} 4 # print(s) # 结果 {1, 4, 23, 55} 5 6 # 1.创建 7 # s = set() 8 # s = {11,22,33,44} 9 10 # 2.转换 11 # l = list() 12 # s = set() #创建集合 13 # s = set([11,2

python基础数据类型之字典+集合

一.数据类型之字典 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的.可哈希表示key必须是不可变类型,如:数字.字符串.元组. 字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型.列表是有序的对象结合,字典是无序的对象集合.两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取. 总结:1.字