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

基础数据类型(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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容